親測可用:
代碼:
1 import sun.misc.BASE64Decoder; 2 import sun.misc.BASE64Encoder; 3 4 import java.io.*; 5 6 public class Base64Util { 7 8 /*把base64編碼轉換為圖片*/ 9 public static boolean generateImage(String imgStr, String path) { 10 if (imgStr == null) 11 return false; 12 BASE64Decoder decoder = new BASE64Decoder(); 13 try { 14 byte[] b = decoder.decodeBuffer(imgStr); 15 for (int i = 0; i < b.length; i++) { 16 if (b[i] < 0) { 17 b[i] += 256; 18 } 19 } 20 OutputStream out = new FileOutputStream(path); 21 out.write(b); 22 out.flush(); 23 out.close(); 24 return true; 25 } catch (Exception e) { 26 e.printStackTrace(); 27 return false; 28 } 29 } 30 31 /*把圖片轉換為base64編碼*/ 32 public static String getImageStr(String imgFile) { 33 InputStream inputStream = null; 34 byte[] data = null; 35 try { 36 inputStream = new FileInputStream(imgFile); 37 data = new byte[inputStream.available()]; 38 inputStream.read(data); 39 inputStream.close(); 40 } catch (IOException e) { 41 e.printStackTrace(); 42 } 43 BASE64Encoder encoder = new BASE64Encoder(); 44 return encoder.encode(data); 45 } 46 /*此為以上方法的用法,可以忽略*/ 47 /*public static void main(String[] args) { 48 *//*把圖片轉換為base64編碼*//* 49 String strImg = getImageStr("這里傳圖片的路徑:c:/users/圖片.png"); 50 System.out.println(strImg); 51 *//*把base64編碼轉換為圖片*//* 52 generateImage(strImg,strImg*//*strImg這里是base64編碼*//*); 53 }*/ 54 }