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

16 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
    Replies
    1. Great Article Image Processing Projects Deep Learning Projects for Final Year JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

      Delete
  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
  5. In some images, you may need to fine tune the colors of your picture, as garish, noisy colors often look awful. Hence you can boost the saturation levels of your image.try this web-site

    ReplyDelete
  6. Hi Thank you for your effort. However, I have a question. How can I pass to MainFrame from another frame.

    ReplyDelete
  7. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I’d prefer to use some with the content on my blog whether you don’t mind. Naturally, I’ll give you a link on your web blog. Thanks for sharing.

    ReplyDelete
  8. The more RAM your laptop has, the better it will run in the grand scheme of things. A lot of RAM means the added ability to run several design programs at once and easily switch between them. web developer nuneaton

    ReplyDelete
  9. Banner advertising is the online marketing equivalent of the traditional ads in newspapers and magazines. It is the free placement of ads on a website usually known as free ad directories.visit this site right here

    ReplyDelete
  10. While marketing is a continuous procedure, the site is frequently viewed as a one-time exertion. In any case, there is in every case additional work to be done: changes and updates, new substance, etc. Sandra Smith

    ReplyDelete
  11. www.norton.com/setup is the best antivirus to prevent web cam take overs and prevents hacking from dark web if you get trouble to re-install norton you can also use norton removal tool

    ReplyDelete
  12. Amazing post. I’m professional Graphic Designer at The Photo Editing. We provide high-quality clipping path service, background removal service, image masking service, neck joint service, ecommerce image editing service, car image editing and photo retouching service at low costs.

    ReplyDelete
  13. Cutout Image Media offers the best quality image editing services. We have been serving since 2010. We can help you with a wide range of image services and clipping path.

    ReplyDelete

Blogroll

Popular Posts