Writing/Reading image in java

By using javax.imageio package, we can read/write images. Here is the code:

import java.awt.*;
import javax.swing.*;
import javax.imageio.*;
import java.awt.image.*;
import java.io.*;

public class CropImage extends JFrame {
Image image;
Insets insets;
BufferedImage img = null;

public CropImage() {
super("Crop Image");
ImageIcon icon = new ImageIcon("Sunset.jpg");
//image = icon.getImage();
//image = createImage(new FilteredImageSource(image.getSource(),
//new CropImageFilter(100, 70, 140, 250)));

try {
img = ImageIO.read(new File("Sunset.jpg"));
File outputfile = new File("saved.gif");
ImageIO.write(img, "gif", outputfile);
} catch (IOException e) {
public void paint(Graphics g) {
if (insets == null) {
insets = getInsets();
g.drawImage(img, insets.left, insets.top, this);
public static void main(String args[]) {
JFrame frame = new CropImage();
frame.setSize(250, 250);


:java.imageio.ImageIO class has a write method
ImageIO.write(img, "gif", outputfile), which takes the image existing in your system path and writes it to desired image format (gif,png..). To read the image file from the system, use img = ImageIO.read(new File("Sunset.jpg")) which returns a BufferedImage reference.

Instead of using javax.imageio, we can use java.awt.image package also, as shown in commented lines.
ImageIcon icon = new ImageIcon("Sunset.jpg");
image = icon.getImage();
image = createImage(new FilteredImageSource(image.
getSource(),new CropImageFilter(100, 70, 140, 250)));

To paint the image:
g.drawImage(img, insets.left, insets.top, this);

But this way, writing the image is not possible.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: