1. 程式人生 > >java 圖片base64互轉

java 圖片base64互轉

++ pan 測試 class encoder col rgs 路徑 div

public class ImgBase64 {
     public static void main(String[] args) //測試
        {
             
            String strImg = GetImageStr();
            System.out.println(strImg);
        }
        public static String GetImageStr()//圖片轉base64
        {//圖片路徑
            String imgFile = "D:\\Users\\sys\\Pictures\\1.png
";// InputStream in = null; byte[] data = null; try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); }
catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(data);// } public static boolean GenerateImage(String imgStr)//base字符串轉圖片 {// if
(imgStr == null) // return false; BASE64Decoder decoder = new BASE64Decoder(); try { byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i]<0) //糾正錯誤字符 { b[i]+=256; } } String imgFilePath = "d:\\222.jpg";// OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }

java 圖片base64互轉