Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Crop an image using Java

This article will tell you how you may crop a given image making use of Java.

In this article we will learn how to crop a given input image and then save that cropped part. This is very easy using java programming. This is helpful in situation where we wish to use only a portion of image.

We are going to perform steps like:

  1. We take an input image i.e. the image from which we wish to crop data from.
  2. Now we allow the user to drag the portion of image which he would like to crop.
  3. After selection we use Robot class to determine the start and end pixel for the cropped area.
  4. Then we take screen shot of that area which has been cropped and this is saved into the disk so that it could be further utilized for various other purpose.

Now, we will start with coding and the explanation part.

Listing1: Importing classes

import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

Here:

  1. Graphics contains method for drawing rectangles, arcs etc
  2. Here we use Rectangle in dragged area concept
  3. Robot class is used for capturing screenshots
  4. We used mouse listener to listen to mouse activities that when and from which point mouse dragging occurred.
  5. BufferedImage is used by Robot class.
  6. File is used to open a file
  7. ImageIO is used to write a png or jpg image from a buffered image
  8. JFrame is used to display a frame

Now we will make the class along with main method

Listing2: Making class along with main method

public class CropImage extends JFrame implements MouseListener, MouseMotionListener
{
	int drag_status=0,c1,c2,c3,c4;
public static void main(String args[])
{
	new CropImage().start();
}

Here

  1. We make a class which is named CropImage.
  2. We use extend frame to have all functionality of frame in this class.
  3. We have implemented various mouse listener because we want to know when user starts to drag an image and from which point.
  4. drag_status variable is for knowing when dragging started and c1,c2,c3,c4 are used for storing coordinates.
  5. We define a main method and then we call a method start from main which we will define later

Now we define the start method

Listing 2: Making class along with main method

public void start()
{
	ImagePanel im=new ImagePanel("F:\\Wallpaper\\wallpapers\\1.jpg");
	add(im);
	setSize(400,400);
	setVisible(true);
	addMouseListener(this);
	addMouseMotionListener( this ); 
	setDefaultCloseOperation(EXIT_ON_CLOSE);
}
  1. We have defined a class named Imagepanel. I will share its source code in final listings.This class help us to show image on the jframe.Here I have given the path of the image a s an argument
  2. We add this image on jframe and make the frame visible as well as make the frame listen to mouse events

Now we define various function defining mouse events

Listing 3: Mouse event functions

@Override
public void mouseClicked(MouseEvent arg0) {	
}

@Override
public void mouseEntered(MouseEvent arg0) {	
}

@Override
public void mouseExited(MouseEvent arg0) {
}

@Override
public void mousePressed(MouseEvent arg0) {
	repaint();
	c1=arg0.getX();
	c2=arg0.getY();
}

@Override
public void mouseReleased(MouseEvent arg0) {
	repaint();
	if(drag_status==1)
	{
	c3=arg0.getX();
	c4=arg0.getY();
	try
	{
	draggedScreen();
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	}
}

@Override
public void mouseDragged(MouseEvent arg0) {
	repaint();
	drag_status=1;
	c3=arg0.getX();
	c4=arg0.getY();
}

@Override
public void mouseMoved(MouseEvent arg0) {
	
}

public void paint(Graphics g)
{
	super.paint(g);
	int w = c1 - c3;
	int h = c2 - c4;
	w = w * -1;
	h = h * -1;
	if(w<0)
		w = w * -1;
    g.drawRect(c1, c2, w, h);
	
}

Here:

  1. When mouse is pressed we store those coordinates in c1 and c2
  2. when mouse is dragged then we set drag_status to true
  3. Now when mouse is released that is picture has been selected then we call the draggedscreen method.
  4. The paint method is responsible for showing the rectangle while dragging the photo.We find the width and height through coordinates and then this is used to make the rectangle.

Now we define draggedscreen method:

Listing 4: Defining draggedScreen method

public void draggedScreen()throws Exception
{
		int w = c1 - c3;
   		int h = c2 - c4;
    	w = w * -1;
    	h = h * -1;
	 	Robot robot = new Robot();
	    BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,w,h));
	    File save_path=new File("screen1.jpg");
	    ImageIO.write(img, "JPG", save_path);
	System.out.println("Cropped image saved successfully.");
}}

Here:

  1. We first find the width and height of image.
  2. We use the robot class to make a screenshot of cropped image and then we save it on disk with name screen1.jpg.

Full Source codes

Listing 5: ImagePanel.java

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JPanel;

	class ImagePanel extends JPanel {

		  private Image img;

		  public ImagePanel(String img) {
		    this(new ImageIcon(img).getImage());
		  }

		  public ImagePanel(Image img) {
		    this.img = img;
		    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
		   // Dimension size = new Dimension(10,10);
		    setPreferredSize(size);
		    setMinimumSize(size);
		    setMaximumSize(size);
		    setSize(size);
		    setLayout(null);
		  }

		  public void paintComponent(Graphics g) {
		    g.drawImage(img, 0, 0, null);
		  }

		}

Listing 6:CropImage.java

import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class CropImage extends JFrame implements MouseListener, MouseMotionListener
{
	int drag_status=0,c1,c2,c3,c4;
public static void main(String args[])
{
	new CropImage().start();
}
public void start()
{
	ImagePanel im=new ImagePanel("F:\\Wallpaper\\wallpapers\\1.jpg");
	add(im);
	setSize(400,400);
	setVisible(true);
	addMouseListener(this);
	addMouseMotionListener( this ); 
	setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void draggedScreen()throws Exception
{
		int w = c1 - c3;
   		int h = c2 - c4;
    	w = w * -1;
    	h = h * -1;
	 	Robot robot = new Robot();
	    BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2,w,h));
	    File save_path=new File("screen1.jpg");
	    ImageIO.write(img, "JPG", save_path);
	System.out.println("Cropped image saved successfully.");
}
@Override
public void mouseClicked(MouseEvent arg0) {		
}

@Override
public void mouseEntered(MouseEvent arg0) {		
}

@Override
public void mouseExited(MouseEvent arg0) {		
}

@Override
public void mousePressed(MouseEvent arg0) {
	repaint();
	c1=arg0.getX();
	c2=arg0.getY();
}

@Override
public void mouseReleased(MouseEvent arg0) {
	repaint();
	if(drag_status==1)
	{
	c3=arg0.getX();
	c4=arg0.getY();
	try
	{
	draggedScreen();
	}
	catch(Exception e)
	{
		e.printStackTrace();
	}
	}
}

@Override
public void mouseDragged(MouseEvent arg0) {
	repaint();
	drag_status=1;
	c3=arg0.getX();
	c4=arg0.getY();
}

@Override
public void mouseMoved(MouseEvent arg0) {
	
}

public void paint(Graphics g)
{
	super.paint(g);
	int w = c1 - c3;
	int h = c2 - c4;
	w = w * -1;
	h = h * -1;
	if(w<0)
		w = w * -1;
    g.drawRect(c1, c2, w, h);	
}
}

This is all for today article. See you next time



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login