Wednesday, 3 November 2021

How to write BufferedImage object to a file?

Using 'ImageIO.write' method, you can write the image to a file.

 

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

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.

 

Step 1: Get the instance of BufferedImage object.

private static BufferedImage getBufferedImage() {
	BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);

	int r = 100;
	int g = 125;
	int b = 55;
	int col = (r << 8) | (g << 16) | b;
	for (int x = 0; x < 300; x++) {
		for (int y = 20; y < 500; y++) {
			img.setRGB(x, y, col);
		}
	}
	return img;
}

 

Step 2: Write buffered image to the file.

File fileToWrite = new File("/Users/Shared/test.png");
ImageIO.write(bufferedImage, "PNG", fileToWrite);

 

Find the below working application.

 

WriteBufferedImage.java

package com.sample.app.images;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class WriteBufferedImage {

	private static BufferedImage getBufferedImage() {
		BufferedImage img = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB);

		int r = 100;
		int g = 125;
		int b = 55;
		int col = (r << 8) | (g << 16) | b;
		for (int x = 0; x < 300; x++) {
			for (int y = 20; y < 500; y++) {
				img.setRGB(x, y, col);
			}
		}
		return img;
	}

	public static void main(String args[]) throws IOException {
		BufferedImage bufferedImage = getBufferedImage();

		File fileToWrite = new File("/Users/Shared/test.png");

		ImageIO.write(bufferedImage, "PNG", fileToWrite);
	}
}

  Run above application and open the file "/Users/Shared/test.png", you will see below kind of screen.

 

  

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment