javafilebufferedimageimgscalr

Image resizing using imgscalr API in java


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.


Solution

  • 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.