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/

  • 相关阅读:
    Kubernetes(十一) 部署doshboard
    kubernetes(一)kubeadm安装
    kubernetes安装-二进制
    使用Jmeter+Maven+Jenkins实现接口自动化测试
    使用Jmeter在linux环境实现分布式负载
    Jmeter连接Mysql和Oracle数据库
    Jmeter如何实现参数化用户,并且管理Cookie
    开启MYSQL慢查询日志,监控有效率问题的SQL
    使用jmeter+ant+jenkins实现接口自动化测试
    使用Jmeter对SHA1加密接口进行性能测试
  • 原文地址:https://www.cnblogs.com/Sharley/p/5591828.html
Copyright © 2011-2022 走看看