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字符串的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: java wcf 未提供用户名_WCF的
- 下一篇: 八叉树 java_java简单实现八叉树
