本篇文章主要介紹了java 后台將base64字符串保存為圖片的方法,現在分享給大家,也給大家做個參考。
1 import java.io.FileInputStream; 2 import java.io.FileNotFoundException; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.OutputStream; 7 8 import Decoder.BASE64Decoder; 9 import Decoder.BASE64Encoder; 10 11 public class Base64Utils { 12 /** 13 * 圖片轉化成base64字符串 14 * @param imgPath 15 * @return 16 */ 17 public static String GetImageStr(String imgPath) {// 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理 18 String imgFile = imgPath;// 待處理的圖片 19 InputStream in = null; 20 byte[] data = null; 21 String encode = null; // 返回Base64編碼過的字節數組字符串 22 // 對字節數組Base64編碼 23 BASE64Encoder encoder = new BASE64Encoder(); 24 try { 25 // 讀取圖片字節數組 26 in = new FileInputStream(imgFile); 27 data = new byte[in.available()]; 28 in.read(data); 29 encode = encoder.encode(data); 30 } catch (IOException e) { 31 e.printStackTrace(); 32 } finally { 33 try { 34 in.close(); 35 } catch (IOException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 } 40 return encode; 41 } 42 43 /** 44 * base64字符串轉化成圖片 45 * 46 * @param imgData 47 * 圖片編碼 48 * @param imgFilePath 49 * 存放到本地路徑 50 * @return 51 * @throws IOException 52 */ 53 @SuppressWarnings("finally") 54 public static boolean GenerateImage(String imgData, String imgFilePath) throws IOException { // 對字節數組字符串進行Base64解碼並生成圖片 55 if (imgData == null) // 圖像數據為空 56 return false; 57 BASE64Decoder decoder = new BASE64Decoder(); 58 OutputStream out = null; 59 try { 60 out = new FileOutputStream(imgFilePath); 61 // Base64解碼 62 byte[] b = decoder.decodeBuffer(imgData); 63 for (int i = 0; i < b.length; ++i) { 64 if (b[i] < 0) {// 調整異常數據 65 b[i] += 256; 66 } 67 } 68 out.write(b); 69 } catch (FileNotFoundException e) { 70 // TODO Auto-generated catch block 71 e.printStackTrace(); 72 } catch (IOException e) { 73 // TODO Auto-generated catch block 74 e.printStackTrace(); 75 } finally { 76 out.flush(); 77 out.close(); 78 return true; 79 } 80 } 81 }
1 public class Test { 2 public static void main(String[] args) throws IOException { 3 String imageStr = Base64Utils.GetImageStr("D://下載/企鵝.jpg"); 4 System.out.println(imageStr); 5 Base64Utils.GenerateImage(imageStr, "D://photos/企鵝.jpg"); 6 } 7 }
圖片編碼如下:
原圖片為:
轉換后為: