[java] How to save a BufferedImage as a File

I am using the imgscalr Java library to resize an image .

The result of a resize() method call is a BufferedImage object. I now want to save this as a file (usually .jpg).

How can I do that? I want to go from BufferedImage -> File but perhaps this is not the correct approach?

This question is related to java file-io bufferedimage

The answer is


You can save a BufferedImage object using write method of the javax.imageio.ImageIO class. The signature of the method is like this:

public static boolean write(RenderedImage im, String formatName, File output) throws IOException

Here im is the RenderedImage to be written, formatName is the String containing the informal name of the format (e.g. png) and output is the file object to be written to. An example usage of the method for PNG file format is shown below:

ImageIO.write(image, "png", file);

File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);

Create and save a java.awt.image.bufferedImage to file:

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );

            File f = new File("MyFile.png");
            int r = 5;
            int g = 25;
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Notes:

  1. Creates a file called MyFile.png.
  2. Image is 500 by 500 pixels.
  3. Overwrites the existing file.
  4. The color of the image is black with a blue stripe across the top.

The answer lies within the Java Documentation's Tutorial for Writing/Saving an Image.

The Image I/O class provides the following method for saving an image:

static boolean ImageIO.write(RenderedImage im, String formatName, File output)  throws IOException

The tutorial explains that

The BufferedImage class implements the RenderedImage interface.

so it's able to be used in the method.

For example,

try {
    BufferedImage bi = getMyImage();  // retrieve image
    File outputfile = new File("saved.png");
    ImageIO.write(bi, "png", outputfile);
} catch (IOException e) {
    // handle exception
}

It's important to surround the write call with a try block because, as per the API, the method throws an IOException "if an error occurs during writing"

Also explained are the method's objective, parameters, returns, and throws, in more detail:

Writes an image using an arbitrary ImageWriter that supports the given format to a File. If there is already a File present, its contents are discarded.

Parameters:

im - a RenderedImage to be written.

formatName - a String containg the informal name of the format.

output - a File to be written to.

Returns:

false if no appropriate writer is found.

Throws:

IllegalArgumentException - if any parameter is null.

IOException - if an error occurs during writing.

However, formatName may still seem rather vague and ambiguous; the tutorial clears it up a bit:

The ImageIO.write method calls the code that implements PNG writing a “PNG writer plug-in”. The term plug-in is used since Image I/O is extensible and can support a wide range of formats.

But the following standard image format plugins : JPEG, PNG, GIF, BMP and WBMP are always be present.

For most applications it is sufficient to use one of these standard plugins. They have the advantage of being readily available.

There are, however, additional formats you can use:

The Image I/O class provides a way to plug in support for additional formats which can be used, and many such plug-ins exist. If you are interested in what file formats are available to load or save in your system, you may use the getReaderFormatNames and getWriterFormatNames methods of the ImageIO class. These methods return an array of strings listing all of the formats supported in this JRE.

String writerNames[] = ImageIO.getWriterFormatNames();

The returned array of names will include any additional plug-ins that are installed and any of these names may be used as a format name to select an image writer.

For a full and practical example, one can refer to Oracle's SaveImage.java example.


  1. Download and add imgscalr-lib-x.x.jar and imgscalr-lib-x.x-javadoc.jar to your Projects Libraries.
  2. In your code:

    import static org.imgscalr.Scalr.*;
    
    public static BufferedImage resizeBufferedImage(BufferedImage image, Scalr.Method scalrMethod, Scalr.Mode scalrMode, int width, int height)  {
        BufferedImage bi = image;
        bi = resize( image, scalrMethod, scalrMode, width, height);
    return bi;
    }
    
    // Save image:
    ImageIO.write(Scalr.resize(etotBImage, 150), "jpg", new File(myDir));
    

As a one liner:

ImageIO.write(Scalr.resize(ImageIO.read(...), 150));

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to file-io

Python, Pandas : write content of DataFrame into text File Saving response from Requests to file How to while loop until the end of a file in Python without checking for empty line? Getting "java.nio.file.AccessDeniedException" when trying to write to a folder How do I add a resources folder to my Java project in Eclipse Read and write a String from text file Python Pandas: How to read only first n rows of CSV files in? Open files in 'rt' and 'wt' modes How to write to a file without overwriting current contents? Write objects into file with Node.js

Examples related to bufferedimage

Java converting Image to BufferedImage How to save a BufferedImage as a File Create a BufferedImage from file and make it TYPE_INT_ARGB Bufferedimage resize How to convert buffered image to image and vice-versa? Java - get pixel array from image Convert RGB values to Integer How to scale a BufferedImage