zoukankan      html  css  js  c++  java
  • Java 图片与byte数组互相转换

     1 //图片到byte数组
     2   public byte[] image2byte(String path){
     3     byte[] data = null;
     4     FileImageInputStream input = null;
     5     try {
     6       input = new FileImageInputStream(new File(path));
     7       ByteArrayOutputStream output = new ByteArrayOutputStream();
     8       byte[] buf = new byte[1024];
     9       int numBytesRead = 0;
    10       while ((numBytesRead = input.read(buf)) != -1) {
    11       output.write(buf, 0, numBytesRead);
    12       }
    13       data = output.toByteArray();
    14       output.close();
    15       input.close();
    16     }
    17     catch (FileNotFoundException ex1) {
    18       ex1.printStackTrace();
    19     }
    20     catch (IOException ex1) {
    21       ex1.printStackTrace();
    22     }
    23     return data;
    24   }
     1   //byte数组到图片
     2   public void byte2image(byte[] data,String path){
     3     if(data.length<3||path.equals("")) return;
     4     try{
     5     FileImageOutputStream imageOutput = new FileImageOutputStream(new File(path));
     6     imageOutput.write(data, 0, data.length);
     7     imageOutput.close();
     8     System.out.println("Make Picture success,Please find image in " + path);
     9     } catch(Exception ex) {
    10       System.out.println("Exception: " + ex);
    11       ex.printStackTrace();
    12     }
    13   }
    14   //byte数组到16进制字符串
    15   public String byte2string(byte[] data){
    16     if(data==null||data.length<=1) return "0x";
    17     if(data.length>200000) return "0x";
    18     StringBuffer sb = new StringBuffer();
    19     int buf[] = new int[data.length];
    20     //byte数组转化成十进制
    21     for(int k=0;k<data.length;k++){
    22       buf[k] = data[k]<0?(data[k]+256):(data[k]);
    23     }
    24     //十进制转化成十六进制
    25     for(int k=0;k<buf.length;k++){
    26       if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k]));
    27       else sb.append(Integer.toHexString(buf[k]));
    28     }
    29     return "0x"+sb.toString().toUpperCase();
    30   } 

    文件解析:
    FileImageOutputStream 换成了 FileOutputStream
    FileImageInputStream 换成 FileInputStream

    转自:http://blog.csdn.net/huang9012/article/details/18241539/

  • 相关阅读:
    2019年Pycharm最新激活码_学生党适用
    Day14_分享昨天看到的一句话
    监督学习算法_k-近邻(kNN)分类算法_源代码
    Python学习需要安装的工具
    Python基础学习资料推荐
    总结一下公司项目使用各种较新的前端技术和 Api 的一些经验。
    由 Session 和 Cookie 的区别说起
    我理解的正确的代码
    回忆我是如何赢得一次踢毽子比赛
    日常的例子说明 throttle 和 debounce 的区别
  • 原文地址:https://www.cnblogs.com/Sharley/p/5591828.html
Copyright © 2011-2022 走看看