日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java图片转成字符串_JAVA将图片(本地或者网络资源)转为Base64字符串,将base64字符串存储为本地图片...

發布時間:2024/10/8 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java图片转成字符串_JAVA将图片(本地或者网络资源)转为Base64字符串,将base64字符串存储为本地图片... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

網絡資源代碼

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

{

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;

}

}

原文:https://www.cnblogs.com/momo1210/p/9708785.html

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的java图片转成字符串_JAVA将图片(本地或者网络资源)转为Base64字符串,将base64字符串存储为本地图片...的全部內容,希望文章能夠幫你解決所遇到的問題。

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