1. 程式人生 > >JAVA高階特性——二進位制儲存圖片

JAVA高階特性——二進位制儲存圖片

import java.io.*;

/**
 * 將圖片轉為陣列,輸出成檔案,再讀取這個檔案,獲得這個陣列,還原成圖片
 * @author Administrator
 *
 *
 */
public class Text3 {
    public static void main(String[] args) {
        //獲取圖片aa.jpg,將圖片資訊儲存到陣列b中
        byte []b=Text3.imgArry("aa.jpg");
        //通過陣列b寫到檔案bb.txt中去
        Text3.writeByteimg(b, "bb.txt");
        
byte []c=Text3.imgin("bb.txt"); Text3.writeimg(c, "cc.jpg"); } /** * 用位元組流獲取圖片,把位元組陣列用ByteArrayOutputStream 寫到 bao裡面去,,可以返回一個位元組陣列 * @param path * @return */ public static byte[] imgArry(String path){ InputStream inImg=null
; ByteArrayOutputStream bao=new ByteArrayOutputStream(); try { inImg=new FileInputStream(path); byte [] b=new byte[1024]; int len=-1; //將圖片的所有位元組通過陣列b讀取出來在寫到bao裡面去 while((len=inImg.read(b))!=-1) { bao.write(b, 0, len); }
//返回bao位元組陣列 return bao.toByteArray(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { bao.close(); inImg.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 用二進位制寫出圖片,儲存到檔案去 * @param imgs * @param path */ public static void writeByteimg(byte []imgs,String path) { DataOutputStream outimg=null; try { outimg=new DataOutputStream(new FileOutputStream(path)); outimg.write(imgs); outimg.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { outimg.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 讀取二進位制儲存的圖片,放到一個位元組陣列中 */ public static byte[] imgin(String path) { DataInputStream imgin=null; try { imgin=new DataInputStream(new FileInputStream(path)); //建立一個位元組陣列,陣列長度等於圖片返回的實際位元組數 byte[] b=new byte[imgin.available()]; //讀取圖片資訊放入b中,返回b imgin.read(b); return b; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { imgin.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } /** * 將圖片輸出 */ public static void writeimg(byte[]img,String path) { OutputStream ow=null; try { ow=new FileOutputStream(path); ow.write(img); ow.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { ow.close(); } catch (IOException e) { e.printStackTrace(); } } } }