图片文件与二进制互转方法


/**
 * @title 读取图片文件将其转为二进制,再生成新的图片
 * 
 */
import java.awt.image.*;
import java.awt.*;
import java.io.*;
import java.sql.Blob;

import javax.imageio.*;

public class test {

 
 /**   
  *   转换byte数组为Image   
  *     
  *   @param   bytes   Image的bytes数据数组   
  *   @param   filename 为要生成新的文件名 
  *   @return   boolean   
  */
 public static boolean ByteToImage(byte[] b,String filename)
 {
  boolean bl=false;
  File binaryFile = new File("D:\\"+filename+".jpg"); 
  try {
   FileOutputStream fileOutStream = new FileOutputStream(binaryFile);
   for(int i=0;i<b.length;i++)
   {
    fileOutStream.write(b[i]);
   }
   fileOutStream.flush(); 
   bl=true;
  } catch (FileNotFoundException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }//创建文件输出流。
  catch (IOException e) {
   // TODO 自动生成 catch 块
   e.printStackTrace();
  }
  return bl;
 }
 

 /*
  * 转换Image数据为byte数组   
  * */
 public static byte[] ImageToBytes(String path)
 {
File file = new File(path);//"C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\示例图片\\Sunset.jpg"
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
} catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
try {
ByteArrayOutputStream out= new ByteArrayOutputStream(); 
int i = fin.read();
while (i != -1) { 
  out.write(i); 
  i= fin.read(); 
return out.toByteArray();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
 }
 
 

 
 public static void main(String args[])
 {

 
byte b[] = ImageToBytes("C:\\Documents and Settings\\All Users\\Documents\\My Pictures\\示例图片\\Sunset.jpg");
   
ByteToImage(b, "2");

 }
}
posted @ 2011-06-23 02:51  Lorn  阅读(3022)  评论(0编辑  收藏  举报