讀取圖片文件將其轉爲二進制,再生成新的圖片
package com.image.test;
/**
* @title 讀取圖片文件將其轉爲二進制,再生成新的圖片
* @author 讓痛苦痛苦
* @缺點: 就是生成的新的圖片顏色有點失真,....希望大家幫忙一起提提意見.本人郵件:[email protected]
*
*/
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("失敗");
}
}