Java sample sharing of cropped and saved images

  • 2020-04-01 02:42:02
  • OfStack

We will learn the following steps:

Enter an image, specifying the path to the image to process
Allows the user to drag and drop parts to be clipped
Select and use the Robot class to determine the coordinates of the clipping section
Crop the selected image and hold
Next we'll start coding.

Listing1: the imported class


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; 

Description:

The Graphics class contains methods for drawing rectangles
We use the Rectangle class as the drag-and-drop Rectangle area for cropping
The Robot class is used to capture screenshots
Use a mouse listener to get the drag time of the mouse
The Robot class USES BufferedImage for image processing
The File class is used to open an image File
The ImageIO class is used to write images to PNG or JPG image files
JFrame is used to display the interface

Now let's write the entry class that contains the main method

Listing2: entrance class


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();  
} 

Description:

I wrote a class called CropImage
This class extends JFrame to implement all the functionality of a frame
Implement different mouse event listeners to know when the user starts dragging the mouse pointer
The drag_status variable is used to hold the coordinates when the mouse starts dragging
We define the main method to call a start method, which is defined below

Next is the start method

Listing 2


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);  
} 

Description:

We define a class called ImagePanel that takes the image to be processed as an argument
Place the ImagePanel to display the image in the JFrame, and start listening for mouse events


Let's define the methods for handling mouse events

Listing 3: mouse event handler


@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);  

} 

Description:

Stores the current coordinates to c1 and c2 when the mouse is pressed
Set the drag status variable drag_status to true when the mouse is pressed and started to drag
When the mouse button is released, the clipping area of the image has been selected, and the draggedscreen method is called
The paint method is used to display the rectangle while dragging, drawing the rectangle from the current coordinates and the coordinates of the initial record

Here is the code for the draggedscreen method


Listing 4: draggedScreen  methods 
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.");  
}} 

Description:

First calculate the height and width of the image
Use the Robot class to take a screenshot of the clipped area and save it to another file, screen1.jpg

Complete code


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);    
}  
} 


Related articles: