2

How to convert Buffered image into a file object. My function actually needs to return a file object . The imgscalr resizing function returns a BufferedImage after resizing.so How to convert it into a file object.

  • BufferedImage represents a decoded image in-memory that any of the Java Image APIs can interact with (which is why imgscalr uses that) -- if you need a File representation of that image data, you need to encode that raw image information and store it, on-disk, as a File before getting the File reference. In that case, @Doorknob's example is exactly right. Writing out the file doesn't just create the File itself, it also runs the image data through the ImageWriter encoder to create an image file (as we know them; JPG, PNG, etc.) – Riyad Kalla Apr 10 '13 at 14:43

1 Answers1

2

Here is an example of writing to a PNG file:

ImageIO.write(yourImage, "PNG", "yourfile.png");

You must import ImageIO (javax.imageio) first, however.

Then you can get the File object for the image with new File("yourfile.png");.

You could put this in a function for ease of use; here is an example:

public File imageToFile(BufferedImage img, String fileName) {
    if (!(fileName.endsWith(".png"))) fileName += ".png";
    ImageIO.write(img, "PNG", filename);
    return new File(fileName);
}

Here is a link to the docs.

You cannot make a file object without saving... well, a file. You could put it in a temporary directory and delete it when you are done using it, though.

tckmn
  • 57,719
  • 27
  • 114
  • 156