package com.fengyunhe.helper.image;
import java.io.*;
/**
* 圖片base64互轉
* Created by yangyan on 2015/8/11.
*/
public class ImageBase64Utils {
public static String bytesToBase64(byte[] bytes) {
return org.apache.commons.codec.binary.Base64.encodeBase64String(bytes);// 返回Base64編碼過的字節數組字符串
}
/**
* 將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
*
* @param path 圖片路徑
* @return base64字符串
*/
public static String imageToBase64(String path) throws IOException {// 將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
byte[] data = null;
// 讀取圖片字節數組
InputStream in = null;
try {
in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return org.apache.commons.codec.binary.Base64.encodeBase64String(data);// 返回Base64編碼過的字節數組字符串
}
/**
* 處理Base64解碼並寫圖片到指定位置
*
* @param base64 圖片Base64數據
* @param path 圖片保存路徑
* @return
*/
public static boolean base64ToImageFile(String base64, String path) throws IOException {// 對字節數組字符串進行Base64解碼並生成圖片
// 生成jpeg圖片
try {
OutputStream out = new FileOutputStream(path);
return base64ToImageOutput(base64, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
/**
* 處理Base64解碼並輸出流
*
* @param base64
* @param out
* @return
*/
public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
if (base64 == null) { // 圖像數據爲空
return false;
}
try {
// Base64解碼
byte[] bytes = org.apache.commons.codec.binary.Base64.decodeBase64(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調整異常數據
bytes[i] += 256;
}
}
// 生成jpeg圖片
out.write(bytes);
out.flush();
return true;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
InputStream bytesInput = HttpClientHelper.INSTANCE.get("http://ww4.sinaimg.cn/bmiddle/66640ec4jw1euxo80dk39j20c80c83z6.jpg", null, null).getEntity().getContent();
byte[] bytes = IOUtils.toByteArray(bytesInput);
String s = ImageBase64Utils.bytesToBase64(bytes);
ImageBase64Utils.base64ToImageFile(s, "d:\\avatar\\test.jpg");