Java將byte[]轉(zhuǎn)圖片存儲到本地的案例
更新時間:2020年10月10日 15:45:48 作者:Curry_BB
這篇文章主要介紹了Java將byte[]轉(zhuǎn)圖片存儲到本地的案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
Java中,將字節(jié)數(shù)組轉(zhuǎn)成圖片的有很多種方式,今天在這里記錄其中一種,方便以后查詢,也可以提供給沒有接觸的童鞋做一個參考。
首先是將圖片轉(zhuǎn)成字節(jié)數(shù)組
import sun.misc.BASE64Encoder; import java.io.*; // 傳入圖片路徑,獲取圖片 FileInputStream fis = new FileInputStream("/Users/curry/error.png"); BufferedInputStream bis = new BufferedInputStream(fis); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buff = new byte[1024]; int len = 0; while ((len = fis.read(buff)) != -1) { bos.write(buff, 0, len); } // 得到圖片的字節(jié)數(shù)組 byte[] result = bos.toByteArray(); // 將數(shù)組轉(zhuǎn)為字符串 BASE64Encoder encoder = new BASE64Encoder(); String str = encoder.encode(result).trim();
將數(shù)組轉(zhuǎn)為圖片
import sun.misc.BASE64Decoder; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; BASE64Decoder decoder = new BASE64Decoder(); byte[] imgbyte = decoder.decodeBuffer("剛剛將字節(jié)數(shù)組轉(zhuǎn)成的字符串"); OutputStream os = new FileOutputStream("/Users/curry/text.png"); os.write(imgbyte, 0, imgbyte.length); os.flush(); os.close();
補充知識:java將圖片轉(zhuǎn)化為base64和base64轉(zhuǎn)化為圖片編碼并保存在本地
我就廢話不多說了,大家還是直接看代碼吧~
public class Base64Convert { /** * @Description: 圖片轉(zhuǎn)化成base64字符串 * @param: path * @Return: */ public static String GetImageStr(String path) { //將圖片文件轉(zhuǎn)化為字節(jié)數(shù)組字符串,并對其進行Base64編碼處理 //待處理的圖片 String imgFile = path; 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(); } //對字節(jié)數(shù)組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); //返回Base64編碼過的字節(jié)數(shù)組字符串 return encoder.encode(data); } /** * @Description: base64字符串轉(zhuǎn)化成圖片 * @param: imgStr * @Return: */ public static boolean GenerateImage(String imgStr,String photoname) { //對字節(jié)數(shù)組字符串進行Base64解碼并生成圖片 //圖像數(shù)據(jù)為空 if (imgStr == null) return false; BASE64Decoder decoder = new BASE64Decoder(); try { //Base64解碼 byte[] b = decoder.decodeBuffer(imgStr); for(int i=0;i<b.length;++i) { if(b[i]<0) { //調(diào)整異常數(shù)據(jù) b[i]+=256; } } //生成jpeg圖片 String imagePath= Config.getUploadPhysicalPath(); //System.currentTimeMillis() //新生成的圖片 String imgFilePath = imagePath+photoname; OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } }
以上這篇Java將byte[]轉(zhuǎn)圖片存儲到本地的案例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring?Boot?Reactor?整合?Resilience4j詳析
這篇文章主要介紹了Spring?Boot?Reactor整合Resilience4j詳析,文章通過引入pom包展開詳細介紹,具有一定的參考價值,感興趣的小伙伴可以參考一下2022-09-09MYSQL批量插入數(shù)據(jù)的實現(xiàn)代碼
非常的實現(xiàn)原理,代碼較多,建議大家仔細看看。2008-10-10