将图像字节[]转换为文件 [英] Convert image byte[] to a file

查看:99
本文介绍了将图像字节[]转换为文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将图像(png,jpg,tiff,gif)转换为磁盘上的文件.将其存储在文件上后查看时,看不到文件.

I am trying to convert an image(png,jpg,tiff,gif) to a File on disk.When I view it after storing it on file, I cannot see the file.

这是我根据其他论坛讨论尝试过的一些代码:

Here is some code I have tried based on other forum discussions:

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文件.

This creates a png file I cannot see.

基于其他讨论,我尝试使用ImageIO,但无法正常使用,感谢您的帮助.

I tried using ImageIO based on some other discussion but can't get it to work.Any help is appreciated.

    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);

推荐答案

您应该将其写入

You should write it to FileOutputStream directly.

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

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

Images are binary data, not character data. You should not use a Writer, it's for character data, but you should use an OutputStream, it's for binary data. The BufferedImage and JPEGImageEncoder are pointless as long as you don't want to manipulate the image.

这篇关于将图像字节[]转换为文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆