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
- Create one panel to display only image using graphics
- Implement mousepressed, mousereleased and mousedrag events and create create rectangular shapes based on these mouse events
- Get sub image of main image with coordinates from above selection
- 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); } }
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.
ReplyDeleteGreat 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
DeleteJoining 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
ReplyDeleteA great deal of the time, they will never be utilized again, so they are typically disposed of promptly. Pink Mirror beauty
ReplyDeleteA 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
ReplyDeleteIn 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
ReplyDeleteHi Thank you for your effort. However, I have a question. How can I pass to MainFrame from another frame.
ReplyDeleteNice 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.
ReplyDeleteThe 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
ReplyDeleteWonderful post . Thanks for share this post.
ReplyDeletephoto retouching services
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
ReplyDeleteWhile 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
ReplyDeletewww.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
ReplyDeleteAmazing 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.
ReplyDeleteThis code is really awesome. clipping usa
ReplyDeleteReally very helpful coding. Best Photo Editing Studio
ReplyDelete