這篇文章將為大家詳細講解有關Java實現將byte[]轉圖片存儲到本地,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
Java中,將字節數組轉成圖片的有很多種方式,今天在這里記錄其中一種,方便以后查詢,也可以提供給沒有接觸的童鞋做一個參考。
首先是將圖片轉成字節數組
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); } // 得到圖片的字節數組 byte[] result = bos.toByteArray(); // 將數組轉為字符串 BASE64Encoder encoder = new BASE64Encoder(); String str = encoder.encode(result).trim();
將數組轉為圖片
import sun.misc.BASE64Decoder; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; BASE64Decoder decoder = new BASE64Decoder(); byte[] imgbyte = decoder.decodeBuffer("剛剛將字節數組轉成的字符串"); OutputStream os = new FileOutputStream("/Users/curry/text.png"); os.write(imgbyte, 0, imgbyte.length); os.flush(); os.close();
補充知識:java將圖片轉化為base64和base64轉化為圖片編碼并保存在本地
我就廢話不多說了,大家還是直接看代碼吧~
public class Base64Convert { /** * @Description: 圖片轉化成base64字符串 * @param: path * @Return: */ public static String GetImageStr(String path) { //將圖片文件轉化為字節數組字符串,并對其進行Base64編碼處理 //待處理的圖片 String imgFile = path; 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(); //返回Base64編碼過的字節數組字符串 return encoder.encode(data); } /** * @Description: base64字符串轉化成圖片 * @param: imgStr * @Return: */ public static boolean GenerateImage(String imgStr,String photoname) { //對字節數組字符串進行Base64解碼并生成圖片 //圖像數據為空 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) { //調整異常數據 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[]轉圖片存儲到本地就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。