I need a method to select a rectangular region from an image (a BufferedImage
into a JLabel
).开发者_JAVA百科
How to implement this using Java?
Is there a ready-to-use component?To select a region of a BufferedImage
, just do:
BufferedImage newImage = yourImage.getSubimage(x, y, width, height);
Adapt the code and provide the parameters x
, y
, width
and height
to define the rectangle.
Important: The new image will be linked to the original! If you update one, the other follows.
See the Javadoc for more info.
EDIT: About the component that will allow the user to select the region, you can do a simple one yourself; or search a pre-made one in libraries like SwingX, ...
If you choose to make a custom component, an approach will be: display the original image and ask the user to click on the first and second points of the rectangle to extract.
You can use a MouseListener
to save the position of the user's clicks and pass these parameters to getSubimage
. This would be an example:
public class RegionSelectorListener extends MouseAdapter {
final JLabel label;
public RegionSelectorListener(JLabel theLabel) {
this.label = theLabel;
theLabel.addMouseListener(this);
}
Point origin = null;
public void mouseClicked(MouseEvent event) {
if (origin == null) { //If the first corner is not set...
origin = event.getPoint(); //set it.
} else { //if the first corner is already set...
//calculate width/height substracting from origin
int width = event.getX() - origin.x;
int height = event.getY() - origin.y;
//output the results (replace this)
System.out.println("Selected X is: "+ origin.x);
System.out.println("Selected Y is: "+ origin.y);
System.out.println("Selected width is: "+ width);
System.out.println("Selected height is: "+ height);
}
}
}
To use it:
new RegionSelectorListener(yourlabel);
精彩评论