Hi frnds!!!!!! Am trying to crop an image using java.. If I draw a rectangle on the image it ll crop the image in the given level.. My code does it but the fact is, it is not cropping the actual part which we selected..This is my code..

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageCropper extends JFrame implements MouseListener, MouseMotionListener {

    //private static final long serialVersionUID = 1L;
    private final JLabel mousePosition;
    int x1, x2, y1, y2;
    int w, h;
    int x3,y3,w3,h3;
    BufferedImage im;
    private final JLabel recStart,k;
    private final JLabel recStop;
    private final JLabel cords; // set up GUI and register mouse event handlers
    //private final ArrayList< Rectangle > rectangles = new ArrayList< Rectangle >();
    private final Vector< Rectangle > rectangles = new Vector< Rectangle >();
    private boolean isNewRect = true;

    public ImageCropper() throws IOException {
      
       
        URL u=getClass().getClassLoader().getResource("crop/sample.jpg");
        im=ImageIO.read(u);
        ImageIcon op=new ImageIcon(im);
        k=new JLabel(op);
                               
        addMouseListener( this ); // listens for own mouse and
        addMouseMotionListener( this ); // mouse-motion events

        setSize( 500, 365 );
        setVisible( true );

    }

    public void mouseClicked( final MouseEvent event ) {
        
        repaint();
    }

    public void mousePressed( final MouseEvent event ) {

        this.x1 = event.getX();
        this.y1 = event.getY();

        repaint();
    }

    public void mouseReleased( final MouseEvent event ) {

        this.x2 = event.getX();
        this.y2 = event.getY();
        
        Rectangle rectangle = getRectangleFromPoints();

        this.rectangles.add( rectangle );
        
        this.w = this.h = this.x1 = this.y1 = this.x2 = this.y2 = 0;
        this.isNewRect = true;

        repaint();
    }

    private Rectangle getRectangleFromPoints() {
        int width = this.x1 - this.x2;
        int height = this.y1 - this.y2;
        Rectangle rectangle = new Rectangle( width < 0 ? this.x1
                : this.x2, height < 0 ? this.y1
                : this.y2, Math.abs( width ), Math.abs( height ) );

        return rectangle;
    }

    public void mouseEntered( final MouseEvent event ) {
        repaint();
    }

    public void mouseExited( final MouseEvent event ) {
        repaint();
    }

    public void mouseDragged( final MouseEvent event ) {
        
        this.x2 = event.getX();
        this.y2 = event.getY();
        this.isNewRect = false;

        repaint();
    }

    public void mouseMoved( final MouseEvent event ) {
        repaint();
    }

    @Override
    public void paint( final Graphics g ) {
        super.paint( g ); // clear the frame surface 

        Rectangle newRectangle = getRectangleFromPoints();
        if ( !this.isNewRect ) {
                g.drawRect( newRectangle.x, newRectangle.y, newRectangle.width, newRectangle.height );
        }
        
        if(rectangles.size()==2){
            rectangles.removeElementAt(0);
        }
                
        for( Rectangle rectangle : this.rectangles ) {
                g.drawRect( rectangle.x, rectangle.y, rectangle.width, rectangle.height );
                //System.out.println(rectangle.x+" "+ rectangle.y+" "+rectangle.width+" "+rectangle.height);
                x3=rectangle.x;
                y3=rectangle.y;
                w3=rectangle.width;
                h3=rectangle.height;
                
        }
        
        this.cords.setText( "w = " + this.w + ", h = " + this.h );
        JButton but=new JButton("segment");
        getContentPane().add(but, BorderLayout.PAGE_END);
        but.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                //BufferedImage subim=im.getSubimage(x3-50, y3-30, w3, h3);
                BufferedImage subim=im.getSubimage(x3, y3, w3, h3);
                
                //System.out.println(x3+" "+y3+" "+w3+" "+h3);
                JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(subim)));
                //throw new UnsupportedOperationException("Not supported yet.");
            }
        });

    }

    public static void main( final String args[] ) throws IOException {
        ImageCropper application = new ImageCropper();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

}

it is not cropping the actual part which we selected.

Is it a problem mapping the selection coordinates to the image's coordinates?
Do you need to consider the image's location on the screen to find the coordinates within the image?

Print out the coordinates for the mouse and for the cropping and the location of the image to see how they are related.


Your code does NOT compile and when the errors are fixed it gets a NullPointerException

Please fix the code so it compiles and executes without errors.

Edited 4 Years Ago by NormR1: n/a

hi buddy!!! This code will work perfectly!! Its showing null exception because you does not have that image in your system frnd!! jus try with other images.. I loaded the image in the line30..It does not getting the coordinates perfectly.. Thats wat my question is frnd!!

I changed the image reference to one of my images.
Where is the variable cords given a value? I get a NPE when this statement is executed:

this.cords.setText( "w = " + this.w + ", h = " + this.h );

The posted code is full of variables that have NOT be initialized!!!

Edited 4 Years Ago by NormR1: n/a

hi frnd!!! Sorryy I posted the old and wrong code unfortunately.. I completed that and here is my code.. I got some doubt why we are minus the y-coordinate in the line 52 to get the correctly cropped image... I am cleared now ... thank you buddy..

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author gowtham
 */
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Vector;
import javax.imageio.ImageIO;
import javax.swing.*;

public class ImageCropper extends JFrame implements MouseListener, MouseMotionListener {

    private static final long serialVersionUID = 1L;
    int x1, x2, y1, y2;
    int w, h;
    int x3,y3,w3,h3;
    BufferedImage im;
    private final JLabel k;
    private final Vector< Rectangle > rectangles = new Vector< Rectangle >();
    private boolean isNewRect = true;

    public ImageCropper() throws IOException {
        super( "Image Cropper" );
        setLayout(null);

        URL u=getClass().getClassLoader().getResource("images/z.jpg");
        im=ImageIO.read(u);
        w=im.getWidth();
        h=im.getHeight();
        ImageIcon op=new ImageIcon(im);
        k=new JLabel(op);
        k.setBounds(0, 0, w, h);
        getContentPane().add(k);
        
        JButton but=new JButton("segment");
        but.setBounds(0, h+10, w, 100);
        getContentPane().add(but);
        but.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                BufferedImage subim=im.getSubimage(x3, y3-30, w3, h3);
                JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(subim)));
            }
        });

        addMouseListener( this ); // listens for own mouse and
        addMouseMotionListener( this ); // mouse-motion events

        setSize( w, h+100 );
        setVisible( true );

    }

    public void mouseClicked( final MouseEvent event ) {
        repaint();
    }

    public void mousePressed( final MouseEvent event ) {
        this.x1 = event.getX();
        this.y1 = event.getY();
        repaint();
    }

    public void mouseReleased( final MouseEvent event ) {
        this.x2 = event.getX();
        this.y2 = event.getY();
        Rectangle rectangle = getRectangleFromPoints();
        this.rectangles.add( rectangle );
        this.x1 = this.y1 = this.x2 = this.y2 = 0;
        this.isNewRect = true;
        repaint();
    }

    private Rectangle getRectangleFromPoints() {
        int width = this.x1 - this.x2;
        int height = this.y1 - this.y2;
        Rectangle rectangle = new Rectangle( width < 0 ? this.x1
                : this.x2, height < 0 ? this.y1
                : this.y2, Math.abs( width ), Math.abs( height ) );

        return rectangle;
    }

    public void mouseEntered( final MouseEvent event ) {
        repaint();
    }

    public void mouseExited( final MouseEvent event ) {
        repaint();
    }

    public void mouseDragged( final MouseEvent event ) {
        this.x2 = event.getX();
        this.y2 = event.getY();
        this.isNewRect = false;
        repaint();
    }

    public void mouseMoved( final MouseEvent event ) {
        repaint();
    }

    @Override
    public void paint( final Graphics g ) {
        super.paint( g ); // clear the frame surface

        Rectangle newRectangle = getRectangleFromPoints();
        if ( !this.isNewRect ) {
                g.drawRect( newRectangle.x, newRectangle.y, newRectangle.width, newRectangle.height );
        }

        if(rectangles.size()==2){
            rectangles.removeElementAt(0);
        }

        for( Rectangle rectangle : this.rectangles ) {
                g.drawRect( rectangle.x, rectangle.y, rectangle.width, rectangle.height );
                x3=rectangle.x;
                y3=rectangle.y;
                w3=rectangle.width;
                h3=rectangle.height;
        }
    }

    public static void main( final String args[] ) throws IOException {
        ImageCropper application = new ImageCropper();
        application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    }

}

Edited 4 Years Ago by javalover: line number changed

Comments
Waste of time posting old code
This question has already been answered. Start a new discussion instead.