最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java 图片与byte数组互相转换实例
时间:2022-06-29 01:41:37 编辑:袖梨 来源:一聚教程网
代码如下 | 复制代码 |
//图片到byte数组 publicbyte[] image2byte(String path){ byte[] data =null; FileImageInputStream input =null; try{ input =newFileImageInputStream(newFile(path)); ByteArrayOutputStream output =newByteArrayOutputStream(); byte[] buf =newbyte[1024]; intnumBytesRead =0; while((numBytesRead = input.read(buf)) != -1) { output.write(buf,0, numBytesRead); } data = output.toByteArray(); output.close(); input.close(); } catch(FileNotFoundException ex1) { ex1.printStackTrace(); } catch(IOException ex1) { ex1.printStackTrace(); } returndata; } //byte数组到图片 publicvoidbyte2image(byte[] data,String path){ if(data.length<3||path.equals(""))return; try{ FileImageOutputStream imageOutput =newFileImageOutputStream(newFile(path)); imageOutput.write(data,0, data.length); imageOutput.close(); System.out.println("Make Picture success,Please find image in "+ path); }catch(Exception ex) { System.out.println("Exception: "+ ex); ex.printStackTrace(); } } //byte数组到16进制字符串 publicString byte2string(byte[] data){ if(data==null||data.length<=1)return"0x"; if(data.length>200000)return"0x"; StringBuffer sb =newStringBuffer(); intbuf[] =newint[data.length]; //byte数组转化成十进制 for(intk=0;k buf[k] = data[k]<0?(data[k]+256):(data[k]); } //十进制转化成十六进制 for(intk=0;k if(buf[k]<16) sb.append("0"+Integer.toHexString(buf[k])); elsesb.append(Integer.toHexString(buf[k])); } return"0x"+sb.toString().toUpperCase(); } |
文件解析:
FileImageOutputStream 换成了 FileOutputStream
FileImageInputStream 换成 FileInputStream
相关文章
- 沙丘觉醒怎么饮血快速解渴 饮血解渴方法介绍 07-15
- 最终幻想14水晶世界居格斯怎么打 强腕的居格斯打法分享 07-15
- 沙丘觉醒怎么更改哈克南厄崔迪家族阵营 阵营转换方法 07-15
- 欧易app注册下载 欧易app交易所v6.7.0 07-15
- 剑星乌龙谷物茶饮料罐在哪 乌龙谷物茶饮料罐收集位置一览 07-15
- 幻兽帕鲁熔岩兽出没地点 帕鲁熔岩兽捕捉位置介绍 07-15