Convert image byte[] to a file

老子叫甜甜 提交于 2020-05-14 11:45:06

问题


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

This creates a png file I cannot see.

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

回答1:


You should write it to FileOutputStream directly.

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

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.




回答2:


What are you trying to do; read a PNG image and save it as a JPEG?

Your first code snippet is not going to work, because you are using a Writer to write the data. A Writer is only suited for writing text files. PNG and JPEG files contain binary data, not text.

You can load an image using the ImageIO API:

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

And then write it in another format using the ImageIO API:

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


来源:https://stackoverflow.com/questions/7211161/convert-image-byte-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!