java實現圖片轉化為位元組流,位元組流還原成圖片
阿新 • • 發佈:2019-01-29
最近,在研究圖片轉化為位元組流以及位元組流還原成圖片的,
程式碼如下:
package com.mybatis.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; public class TestImage { public static void main(String[] args) throws Exception { //先模擬一個圖形byte[] byte[] b1 =image2Bytes("d:\\1.jpg"); //存為檔案 buff2Image(b1,"d:\\test.jpg"); System.out.println("Hello World!"); } static void buff2Image(byte[] b,String tagSrc) throws Exception { FileOutputStream fout = new FileOutputStream(tagSrc); //將位元組寫入檔案 fout.write(b); fout.close(); } static byte[] image2Bytes(String imgSrc) throws Exception { FileInputStream fin = new FileInputStream(new File(imgSrc)); //可能溢位,簡單起見就不考慮太多,如果太大就要另外想辦法,比如一次傳入固定長度byte[] byte[] bytes = new byte[fin.available()]; //將檔案內容寫入位元組陣列,提供測試的case fin.read(bytes); fin.close(); return bytes; } }