0

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);
bluish
  • 26,356
  • 27
  • 122
  • 180
Vijay
  • 595
  • 1
  • 13
  • 27

2 Answers2

5

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • 1
    +1 as I was unable to answer this question myself, was busy reattaching my jaw after reading the code... – Matt Ball Aug 26 '11 at 22:44
  • @BlausC I have a use case for Android OS to copy a .png image as an app asset. So rather than use IOUtils from Apache library, can you point me in the right direction to copy the image bytes to a file with Android methods, so I can use FileProvider() to share the image with another app user? I am trying to copy image to a File in the app's internal storage directory. – AJW May 13 '20 at 22:15
  • 1
    @AJW: https://stackoverflow.com/search?q=%5Bjava%5D+write+inputstream+to+outputstream --> https://stackoverflow.com/q/43157/157882 – BalusC May 13 '20 at 22:26
0

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"));
Jesper
  • 202,709
  • 46
  • 318
  • 350