We can select rectangular area of an image using  Image editing tools. Here in this article, I am going to implement this feature with Java.

Program Flow

  1. Create one panel to display only image using graphics
  2. Implement mousepressed, mousereleased and mousedrag events and create create rectangular shapes based on these mouse events
  3. Get sub image of main image with coordinates from above selection
  4. Update selected area panel with above sub image 

ImagePanel.java

This class extends JPanel. It implements mouse events and it is responsible for user selection of image. Whenever user select rectangular area, it will trigger main panel to update selected region.
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private BufferedImage image;
    private Shape shape = null;
    Point startDrag, endDrag;

    public ImagePanel( String inputImage, MainFrame mf1) throws IOException {
        final MainFrame mf = mf1;
        image = ImageIO.read(new File(inputImage));
        this.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                startDrag = new Point(e.getX(), e.getY());
                endDrag = startDrag;
                repaint();
            }

            public void mouseReleased(MouseEvent e) {
                if(endDrag!=null && startDrag!=null) {
                    try {
                        shape = makeRectangle(startDrag.x, startDrag.y, e.getX(),
                                e.getY());
                        mf.updateSelectedRegion(image.getSubimage(startDrag.x, startDrag.y, e.getX()-startDrag.x, e.getY()-startDrag.y));   
                        startDrag = null;
                        endDrag = null;
                        repaint();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }   
                }
            }
        });

        this.addMouseMotionListener(new MouseMotionAdapter() {
            public void mouseDragged(MouseEvent e) {
                endDrag = new Point(e.getX(), e.getY());
                repaint();
            }   
        });
    }

    
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.drawImage(image, 0, 0, null);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        
        g2.setStroke(new BasicStroke(2));
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                0.50f));

        if (shape != null) {
            g2.setPaint(Color.BLACK);
            g2.draw(shape);
            g2.setPaint(Color.YELLOW);
            g2.fill(shape);
        }
        
        if (startDrag != null && endDrag != null) {
            g2.setPaint(Color.LIGHT_GRAY);
            Shape r = makeRectangle(startDrag.x, startDrag.y, endDrag.x,
                    endDrag.y);
            g2.draw(r);
        }
        
    }

    private Rectangle2D.Float makeRectangle(int x1, int y1, int x2, int y2) {
        return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2),
                Math.abs(x1 - x2), Math.abs(y1 - y2));
    }
    
}

MainFrame.java

This is the main window which has Image Panel and Selected area panel. Here update imagePath variable with your image file path.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;

public class MainFrame {

    private JFrame frmSelectAreaIn;
    private JPanel selectedAreaPanel;
    private String imagePath="C:\\inputImage.jpg";
    
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MainFrame window = new MainFrame();
                    window.frmSelectAreaIn.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     * @throws IOException 
     */
    public MainFrame() throws IOException {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     * @throws IOException 
     */
    private void initialize() throws IOException {
        frmSelectAreaIn = new JFrame();
        frmSelectAreaIn.setTitle("Select Area In Image");
        frmSelectAreaIn.setBounds(100, 100, 708, 370);
        frmSelectAreaIn.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmSelectAreaIn.getContentPane().setLayout(null);
        
        // Image Panel display selected area of the image
        selectedAreaPanel = new JPanel();
        selectedAreaPanel.setBounds(469, 36, 221, 289);
        frmSelectAreaIn.getContentPane().add(selectedAreaPanel);
        
        // Image Panel display image with graphics
        JPanel mainPanel = new ImagePanel(imagePath, this);
        mainPanel.setBounds(10, 11, 449, 314);
        frmSelectAreaIn.getContentPane().add(mainPanel);
        
        JLabel lblSelectedArea = new JLabel("Selected Area");
        lblSelectedArea.setBounds(469, 11, 221, 14);
        frmSelectAreaIn.getContentPane().add(lblSelectedArea);
    }

    // function to update selected region of the image
    public void updateSelectedRegion(BufferedImage bufferedImage) {
        Graphics g = selectedAreaPanel.getGraphics();
        g.clearRect(0, 0, 221, 289);
        g.drawImage(bufferedImage, 0, 0, null);
    }
}

4 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training in India . Nowadays Java has tons of job opportunities on various vertical industry.

    ReplyDelete
  2. Joining is just fundamental in the event that you need to share your photos on the web, else you can simply visit the site and open up the application!https://photolemur.com/photo-editor

    ReplyDelete
  3. A great deal of the time, they will never be utilized again, so they are typically disposed of promptly. Pink Mirror beauty

    ReplyDelete
  4. A few, for example, GIMP are extremely exceptionally prominent. For direct photo editing, thoroughly free online picture editors, for example, Picasa could be all you require. clipping path service

    ReplyDelete

Blogroll

Follow this blog by Email

Popular Posts