2011-08-26 127 views
0

我试图将图像(PNG,JPG,TIFF,GIF)转换为磁盘上的文件。当我在将文件存储到文件后查看它时,我看不到该文件。将图像byte []转换为文件

下面是一些代码基于其他论坛讨论我曾尝试:

byte[] inFileName = org.apache.commons.io.FileUtils.readFileToByteArray(new File("c:/test1.png")); 

InputStream inputStream = new ByteArrayInputStream(inFilename); 
..String fileName="test.png"; 
Writer writer = new FileWriter(fileName); 
IOUtils.copy(inputStream, writer,"ISO-8859-1"); 

这将创建一个PNG文件,我不能看。

我尝试使用基于其他讨论的ImageIO,但不能得到它的工作。任何帮助表示赞赏。

Image inImage = ImageIO.read(new ByteArrayInputStream(inFilename)); 
BufferedImage outImage = new BufferedImage(100, 100, 
      BufferedImage.TYPE_INT_RGB); 
OutputStream os = new FileOutputStream(fileName); 
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os); 
//encoder.encode(inImage); 
+3

做我的眼睛骗我?你真的**写了一个文本编码的PNG文件吗? –

+0

http://stackoverflow.com/questions/1580038/byte-array-to-image-file – Vijay

+0

http://stackoverflow.com/questions/1580038/byte-array-to-image-file – Vijay

回答

2

您应该直接写入FileOutputStream

InputStream input = new ByteArrayInputStream(bytes); 
OutputStream output = new FileOutputStream(fileName); 
IOUtils.copy(input, output); 

图像是二进制数据,而不是字符数据。您不应该使用Writer,它是用于字符数据的,但您应该使用OutputStream,它用于二进制数据。只要你不想操纵图像,BufferedImageJPEGImageEncoder就毫无意义。

+1

+1因为我是我自己无法回答这个问题,在阅读完代码后正忙着重新贴上我的下巴...... –

0

你想做什么;读一个PNG图像并保存为JPEG?

您的第一个代码段不起作用,因为您正在使用Writer来编写数据。 A Writer仅适用于编写文本文件。 PNG和JPEG文件包含二进制数据,而不是文本。

您可以使用ImageIO的API加载图像:

BufferedImage img = ImageIO.read(new File("C:/test.png")); 

,然后使用ImageIO的API以另一种格式写:

ImageIO.write(img, "jpg", new File("C:/test.jpg")); 
相关问题