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/