關于JAVA11中圖片與BASE64相互轉換的實現
更新時間:2021年04月21日 09:50:22 作者:一個不想學習的程序員
這篇文章主要介紹了關于JAVA11中圖片與BASE64相互轉換的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
由于jdk 1.8 之后sun.misc 包下的 BASE64Decode的依賴 被移除
我們需要在自己的項目中引入EncodeUtils 工具類 幫助我們進行轉換
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); } }
在項目中測試
直接調用工具類中的方法即可
/*** * <p> * description: base64字符串轉圖片 * <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:圖片轉base64字符串: * <p> * @see */ public static String getImgStr(String imgFile) { // 將圖片文件轉化為字節(jié)數組字符串,并對其進行Base64編碼處理 InputStream in = null; byte[] data = null; // 讀取圖片字節(jié)數組 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); }
運行結果
圖片轉BASE64 效果圖
BASE64 轉圖片 效果圖
(注:這個生成的圖片路徑就是自己在base64StringToImage 方法中的路徑)
到此這篇關于關于JAVA11中圖片與BASE64相互轉換的實現的文章就介紹到這了,更多相關JAVA11圖片與BASE64相互轉換內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring使用RestTemplate模擬form提交示例
本篇文章主要介紹了Spring使用RestTemplate模擬form提交示例,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03關于SpringMVC中數據綁定@ModelAttribute注解的使用
這篇文章主要介紹了關于SpringMVC中數據綁定@ModelAttribute注解的使用,SpringMVC是一個基于Spring框架的Web框架,它提供了一種簡單、靈活的方式來開發(fā)Web應用程序,在開發(fā)Web應用程序時,我們需要將用戶提交的數據綁定到我們的Java對象上,需要的朋友可以參考下2023-07-07淺談java中replace()和replaceAll()的區(qū)別
這篇文章主要介紹了java中replace()和replaceAll()的區(qū)別,兩者都是常用的替換字符的方法,感興趣的小伙伴們可以參考一下2015-11-11