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(); } } } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM