1. 程式人生 > >JAVA將圖片(本地或者網絡資源)轉為Base64字符串,將base64字符串存儲為本地圖片

JAVA將圖片(本地或者網絡資源)轉為Base64字符串,將base64字符串存儲為本地圖片

.com 返回 ++ path cat 地圖 flush ++i 圖片

網絡資源代碼

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
* 將網絡圖片轉成Base64碼,此方法可以解決解碼後圖片顯示不完整的問題
* @param imgURL圖片地址。
* 例如:http://***.com/271025191524034.jpg
* @return
*/
public static String imgBase64(String imgURL) {
ByteArrayOutputStream outPut = new ByteArrayOutputStream();
byte[] data = new byte[1024];
try {
// 創建URL
URL url = new URL(imgURL);
// 創建鏈接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(10 * 1000);

if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "fail";//連接失敗/鏈接失效/圖片不存在
}
InputStream inStream = conn.getInputStream();
int len = -1;
while ((len = inStream.read(data)) != -1) {
outPut.write(data, 0, len);
}
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 對字節數組Base64編碼
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(outPut.toByteArray());
}

本地圖片轉base64

public static String GetImageStr(String imgFile)
{//將圖片文件轉化為字節數組字符串,並對其進行Base64編碼處理
InputStream in = null;
byte[] data = null;
//讀取圖片字節數組
try
{
in = new FileInputStream(imgFile);
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 base64str,String savepath)
{ //對字節數組字符串進行Base64解碼並生成圖片
if (base64str == null) //圖像數據為空
return false;
// System.out.println("開始解碼");
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解碼
byte[] b = decoder.decodeBuffer(base64str);
// System.out.println("解碼完成");
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{//調整異常數據
b[i]+=256;
}
}
// System.out.println("開始生成圖片");
//生成jpeg圖片
OutputStream out = new FileOutputStream(savepath);
out.write(b);
out.flush();
out.close();
return true;
}
catch (Exception e)
{
return false;
}
}

JAVA將圖片(本地或者網絡資源)轉為Base64字符串,將base64字符串存儲為本地圖片