將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理,以及對字節數組字符串進行Base64解碼並生成圖片


實際開發中涉及圖片上傳並且量比較大的時候一般處理方式有三種

1、直接保存到項目中 最老土直接方法,也是最不適用的方法,量大對后期部署很不方便

2、直接保存到指定路徑的服務器上、需要時候在獲取,這種方式很方便

3、直接保存到數據庫中,需要時候解碼在生成圖片 下面介紹第三種方式

// 將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理

public static String GetImageStr(File file) {
byte[] data = null;
// 讀取圖片字節數組
try {
InputStream in = new FileInputStream(file);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64編碼過的字節數組字符串
}

 

// 對字節數組字符串進行Base64解碼並生成圖片

public static boolean GenerateImage(String imgStr, String imgFilePath) {
if (imgStr == null) // 圖像數據為空
return false;
System.out.println("照片:"+imgStr);
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調整異常數據
bytes[i] += 256;
}
}
// 生成jpeg圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM