Archive for category Java Swing

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.*;

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 = 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,, 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 = 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,, this);

But this way, writing the image is not possible.

Leave a comment