網(wǎng)絡(luò)圖片轉(zhuǎn)BASE64
? ? ? ? ? ?String encoder = "data:image/jpg;base64,"; //定義圖片類型,方便前端直接使用
? ? ? ?? ? ?ByteArrayOutputStream data = new ByteArrayOutputStream();
URL url = new URL(picUrl);//picUrl為圖片地址
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream is = connection.getInputStream();
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//這里去掉結(jié)果里面的"\r\n",也可以不去,但是不去的話需要使用的時(shí)候還是要去掉,所以為了方便就先去掉再存儲(chǔ)
如果是本地圖片的話,其實(shí)和網(wǎng)絡(luò)圖片相差不多的,主要就是讀取圖片流的形式變一下文章來源:http://www.zghlxwxcb.cn/news/detail-543355.html
? ? String encoder = "data:image/jpg;base64,"; //定義圖片類型,方便前端直接使用
? ? ByteArrayOutputStream data = new ByteArrayOutputStream();
? ? String filePath = "filePath";//這里的filePath為本地存放圖片的地址
? ? FileInputStream is = new FileInputStream(filePath);
? byte[] bytes = new byte[1024];
? int len = 0;
while ((len = is.read(bytes)) != -1){
data.write(bytes,0,len);
}
is.close();
BASE64Encoder base64Encoder = new BASE64Encoder();
encoder = encoder + base64Encoder.encode(data.toByteArray()).replace("\r\n","").trim();//這里去掉結(jié)果里面的"\r\n",也可以不去,但是不去的話需要使用的時(shí)候還是要去掉,所以為了方便就先去掉再存儲(chǔ)
若有問題,可以留言探討。文章來源地址http://www.zghlxwxcb.cn/news/detail-543355.html
到了這里,關(guān)于JAVA實(shí)現(xiàn)網(wǎng)絡(luò)/本地圖片轉(zhuǎn)BASE64存儲(chǔ)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!