Rad*_*adi 1 java user-interface image
我需要一种从图像(a BufferedImage到a JLabel)中选择矩形区域的方法.
当用户选择区域时,我需要保存矩形的四个点(像素位置).
如何使用Java实现这一点?
是否有现成的组件?
要选择a的某个区域BufferedImage,只需执行以下操作:
BufferedImage newImage = yourImage.getSubimage(x, y, width, height);
Run Code Online (Sandbox Code Playgroud)
适应代码,并提供该参数x,y,width并height以限定矩形.
重要提示:新图像将链接到原始图像!如果您更新一个,则另一个更新.
有关详细信息,请参阅Javadoc.
编辑:关于允许用户选择区域的组件,您可以自己做一个简单的组件; 或在SwingX等图书馆中搜索预制的,......
如果您选择制作自定义组件,则方法是:显示原始图像并要求用户单击要提取的矩形的第一个和第二个点.
您可以使用a MouseListener来保存用户点击的位置并将这些参数传递给getSubimage.这将是一个例子:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
要使用它:
new RegionSelectorListener(yourlabel);
Run Code Online (Sandbox Code Playgroud)