Java 图片与byte数组互相转换

本文介绍了如何将图片转换为字节数组以及如何从字节数组还原图片的方法,并提供了将字节数组转换为16进制字符串的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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.youkuaiyun.com/huang9012/article/details/18241539/

转载于:https://www.cnblogs.com/Sharley/p/5591828.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值