日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

java图片转换成base64_Java将图片转换成Base64字符串

發布時間:2025/3/19 45 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java图片转换成base64_Java将图片转换成Base64字符串 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

public classImageUtil {/*** 本地圖片轉換成base64字符串

*@paramimgFile

* 圖片本地路徑

*@return

*/

public static String ImageToBase64ByLocal(String imgFile) {//將圖片文件轉化為字節數組字符串,并對其進行Base64編碼處理

InputStream in = null;byte[] data = null;//讀取圖片字節數組

try{

in= newFileInputStream(imgFile);

data= new byte[in.available()];

in.read(data);

in.close();

}catch(IOException e) {

e.printStackTrace();

}//對字節數組Base64編碼

BASE64Encoder encoder = newBASE64Encoder();return encoder.encode(data);//返回Base64編碼過的字節數組字符串

}/*** base64字符串轉換成圖片

*@paramimgStr

* base64字符串

*@paramimgFilePath

* 圖片存放路徑

*@return

*/

public static boolean Base64ToImage(String imgStr, String imgFilePath) { //對字節數組字符串進行Base64解碼并生成圖片

if (StringUtil.isNullOrEmpty(imgStr)) { //圖像數據為空

return false;

}

BASE64Decoder decoder= newBASE64Decoder();try{//Base64解碼

byte[] b =decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {//調整異常數據

b[i] += 256;

}

}

OutputStream out= newFileOutputStream(imgFilePath);

out.write(b);

out.flush();

out.close();return true;

}catch(Exception e) {return false;

}

}public static byte[] Base64ToByte(String imgStr) {if (StringUtil.isNullOrEmpty(imgStr)) { //圖像數據為空

return null;

}

BASE64Decoder decoder= newBASE64Decoder();try{//Base64解碼

byte[] b =decoder.decodeBuffer(imgStr);for (int i = 0; i < b.length; ++i) {if (b[i] < 0) {//調整異常數據

b[i] += 256;

}

}returnb;

}catch(Exception e) {return null;

}

}public staticInputStream Base64ToInputStream(String imgStr) {byte[] b =Base64ToByte(imgStr);if(null ==b) {return null;

}

ByteArrayInputStream bais= newByteArrayInputStream(b);returnbais;

}public staticString handleBase64Str(String base64Str) {

String markStr= "base64,";int indexOf =base64Str.indexOf(markStr);if(indexOf != -1) {return base64Str.substring(indexOf +(markStr.length()));

}returnbase64Str;

}

}

總結

以上是生活随笔為你收集整理的java图片转换成base64_Java将图片转换成Base64字符串的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。