1
我需要一种方法从图像中选择一个矩形区域(BufferedImage
到JLabel
)。
当用户选择一个区域时,我需要保存矩形的四个点(像素位置)。选择图像的区域
如何使用Java实现这个?
是否有即用型组件?
我需要一种方法从图像中选择一个矩形区域(BufferedImage
到JLabel
)。
当用户选择一个区域时,我需要保存矩形的四个点(像素位置)。选择图像的区域
如何使用Java实现这个?
是否有即用型组件?
要选择BufferedImage
的区域,只是做:
BufferedImage newImage = yourImage.getSubimage(x, y, width, height);
适应代码,并提供该参数x
,y
,width
和height
定义的矩形。
重要提示:新图像将是链接到原来!如果你更新了一个,那么下一个。
查看Javadoc了解更多信息。
编辑:关于将允许用户选择区域,你可以自己做一个简单的组件;或搜索预先制作一个像SwingX图书馆,...
如果你选择做一个自定义组件,这种做法将是:显示原始图像和要求用户点击在第一和秒要提取的矩形点。
您可以使用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);
}
}
}
要使用它:
new RegionSelectorListener(yourlabel);
感谢您的帮助,我知道如何做到这一步,但我需要知道如何捕捉来自用户的选择矩形点在图像上(在GUI中)? – Radi 2011-05-01 18:35:12
@radi看我的编辑。它应该给你一个想法。如果您有任何疑问,请告诉我! – 2011-05-01 19:00:05
在此先感谢 – Radi 2011-05-01 19:23:20