读取图片文件将其转为二进制,再生成新的图片
package com.image.test;
/**
* @title 读取图片文件将其转为二进制,再生成新的图片
* @author 让痛苦痛苦
* @缺点: 就是生成的新的图片颜色有点失真,....希望大家帮忙一起提提意见.本人邮件:zhusehaui@yahoo.com.cn
*
*/
import java.awt.image.*;
import java.awt.*;
import java.awt.Image;
import java.io.*;
import javax.imageio.*;
public class ImageByte {
/**
* 转换Image数据为byte数组
*
* @param image Image对象
* @param format image格式字符串.如"jpeg","png"
* @return byte数组
*/
public static byte[] imageToBytes(BufferedImage image, String format)
{
BufferedImage bImage = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_ARGB);
Graphics bg = bImage.getGraphics();
bg.drawImage(image, 0, 0, null);
bg.dispose();
ByteArrayOutputStream out = new ByteArrayOutputStream();
try
{
ImageIO.write(bImage, format, out);
}
catch (IOException e)
{
e.printStackTrace();
// Log.log(null,"imageToBytes(): "+e);
}
return out.toByteArray();
}
/**
* 转换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://test//"+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;
}
/**
* 转换byte数组为Image
*
* @param bytes Image的bytes数据数组
* @return Image
*/
public static Image bytesToImage(byte[] bytes)
{
Image image = Toolkit.getDefaultToolkit().createImage(bytes);
try
{
MediaTracker mt = new MediaTracker(new Label());
mt.addImage(image, 0);
mt.waitForAll();
}
catch (InterruptedException e)
{
e.printStackTrace();
// Log.log(null, "preloadResource(): " + e);
}
return image;
}
static byte[] b=null;
public static void main(String args[])
{
File file = new File("C://Documents and Settings//zhuseahui.4AD701D74BE041A//My Documents//picture//1梦之樱璐.jpg");
BufferedImage src;
try {
src = javax.imageio.ImageIO.read(file);
b=new ImageByte().imageToBytes(src, "jpeg");
System.out.println("b.length======="+b.length);
// for(int i=0;i<b.length;i++)
// {
System.out.println(b[i]);
// }
// new ImageByte().bytesToImage(b);
} catch (IOException e) {
e.printStackTrace();
} //构造Image对象
if(new ImageByte().ByteToImage(b, "2"))
System.out.println("文件从流中成功读出");
else
System.out.println("失败");
}
}