一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java 图片与byte数组互相转换实例

时间:2017-04-14 编辑:简简单单 来源:一聚教程网

 代码如下 复制代码

//图片到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


热门栏目