java 从java中的现有图像中剪切图像的一部分
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2987139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
cut part of an image from an existing image in java
提问by Julio
Currently working in Java, i'd like to be able to select part of an image using the mouse pointer co ordinates. The area selected then needs to be cut from the existing image and used to create a new separate image.
目前在 Java 中工作,我希望能够使用鼠标指针坐标选择图像的一部分。然后需要从现有图像中剪切所选区域并用于创建新的单独图像。
Just like a few pointers on how to go about it. Thanks.
就像一些关于如何去做的指针一样。谢谢。
回答by aioobe
If you want the user to be able to "click-and-drag" to select a rectangle you need to implement a MouseMotionListener. Have a look at the mouseDraggedmethod:
如果您希望用户能够“单击并拖动”来选择一个矩形,您需要实现一个MouseMotionListener. 看看mouseDragged方法:
void mouseDragged(MouseEvent e)
Invoked when a mouse button is pressed on a component and then dragged.
void mouseDragged(MouseEvent e)
在组件上按下鼠标按钮然后拖动时调用。
When you need to get hold of the sub-image, you simply use
当您需要获取子图像时,您只需使用
public BufferedImage getSubimage(int x, int y, int w, int h)
Returns a subimage defined by a specified rectangular region. The returned BufferedImage shares the same data array as the original image.
public BufferedImage getSubimage(int x, int y, int w, int h)
返回由指定矩形区域定义的子图像。返回的 BufferedImage 与原始图像共享相同的数据数组。
If you want to save the resulting image to disk, I suggest you have a look at Saving a Generated Graphic to a PNG or JPEG File.
如果要将生成的图像保存到磁盘,建议您查看将生成的图形保存到 PNG 或 JPEG 文件。
回答by trashgod
If you just want a usable tool or to see how it's done in Java, try ImageJ. If you want to write your own tool, have a look at Working with Imagesand How to Write a Mouse Listener. Once you have a BufferedImageand the desired coordinates, drawImage()will do most of what you want.
如果您只是想要一个可用的工具或想看看它是如何在 Java 中完成的,请尝试ImageJ。如果您想编写自己的工具,请查看使用图像和如何编写鼠标侦听器。一旦你有了一个BufferedImage和所需的坐标,drawImage()就会做你想做的大部分事情。

