關(guān)于JAVA11中圖片與BASE64相互轉(zhuǎn)換的實現(xiàn)
由于jdk 1.8 之后sun.misc 包下的 BASE64Decode的依賴 被移除
我們需要在自己的項目中引入EncodeUtils 工具類 幫助我們進行轉(zhuǎn)換
public class EncodeUtils {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
/**
* Base64編碼.
*/
public static String base64Encode(byte[] input) {
return new String(Base64.encodeBase64(input));
}
/**
* Base64解碼.
*/
public static byte[] base64Decode(String input) {
return Base64.decodeBase64(input);
}
}
在項目中測試
直接調(diào)用工具類中的方法即可
/***
* <p>
* description: base64字符串轉(zhuǎn)圖片
* <p>
* @see
*/
static void base64StringToImage(String base64String) {
try {
byte[] bytes1 = EncodeUtils.base64Decode(base64String);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
BufferedImage bi1 = ImageIO.read(bais);
File f1 = new File("F:/wpcache/test/test.jpg");
ImageIO.write(bi1, "jpg", f1);
} catch (IOException e) {
e.printStackTrace();
}
}
/***
* <p>
* description:圖片轉(zhuǎn)base64字符串:
* <p>
* @see
*/
public static String getImgStr(String imgFile) {
// 將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對其進行Base64編碼處理
InputStream in = null;
byte[] data = null;
// 讀取圖片字節(jié)數(shù)組
try {
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return EncodeUtils.base64Encode(data);
}
在main方法中運行
public static void main(String[] args) {
String base64Str = getImgStr("F:/wpcache/2.jpg");
System.out.println(base64Str);
base64StringToImage(base64Str);
}
運行結(jié)果
圖片轉(zhuǎn)BASE64 效果圖

BASE64 轉(zhuǎn)圖片 效果圖
(注:這個生成的圖片路徑就是自己在base64StringToImage 方法中的路徑)

到此這篇關(guān)于關(guān)于JAVA11中圖片與BASE64相互轉(zhuǎn)換的實現(xiàn)的文章就介紹到這了,更多相關(guān)JAVA11圖片與BASE64相互轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實現(xiàn)將文件上傳到ftp服務(wù)器的方法
這篇文章主要介紹了java實現(xiàn)將文件上傳到ftp服務(wù)器的方法,結(jié)合實例形式分析了基于java實現(xiàn)的ftp文件傳輸類定義與使用方法,需要的朋友可以參考下2016-08-08
Spring使用RestTemplate模擬form提交示例
本篇文章主要介紹了Spring使用RestTemplate模擬form提交示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
關(guān)于SpringMVC中數(shù)據(jù)綁定@ModelAttribute注解的使用
這篇文章主要介紹了關(guān)于SpringMVC中數(shù)據(jù)綁定@ModelAttribute注解的使用,SpringMVC是一個基于Spring框架的Web框架,它提供了一種簡單、靈活的方式來開發(fā)Web應(yīng)用程序,在開發(fā)Web應(yīng)用程序時,我們需要將用戶提交的數(shù)據(jù)綁定到我們的Java對象上,需要的朋友可以參考下2023-07-07
淺談java中replace()和replaceAll()的區(qū)別
這篇文章主要介紹了java中replace()和replaceAll()的區(qū)別,兩者都是常用的替換字符的方法,感興趣的小伙伴們可以參考一下2015-11-11

