用类在Java中裁剪图像?
我已经尝试这样做大约一周了。每次我尝试某件事都会失败。所以我转向复制其他代码...他们说该代码对他们有用...但对我来说却失败了。
我最终喜欢的代码来自以下内容。
如何在 Java 中裁剪图像 (StackOverflow)
那么从我基本上复制/制作了这个。
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
public class ImageEditor {
public BufferedImage crop(BufferedImage src, Rectangle rect) {
BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = dest.getGraphics();
g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null);
g.dispose();
return dest;
}
}
我用这段代码得到了以下错误。
提前感谢您的帮助!
I have been attempting to do this for about a week. Every single time I have tried something it failed. So I turned to copying others code... they said the code worked for them... yet it failed for me.
The piece of code that I ended up liking came from the following.
How To Crop Image in Java (StackOverflow)
So then from that I basically copied / made this.
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
public class ImageEditor {
public BufferedImage crop(BufferedImage src, Rectangle rect) {
BufferedImage dest = new BufferedImage(rect.getWidth(), rect.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics g = dest.getGraphics();
g.drawImage(src, 0, 0, rect.getWidth(), rect.getHeight(), rect.getX(), rect.getY(), rect.getX() + rect.getWidth(), rect.getY() + rect.getHeight(), null);
g.dispose();
return dest;
}
}
I got the following errors with this code.
Thanks for the help in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个错误表示找不到方法
drawImage(BufferedImage,int,int,double,double,double,double,double,double,)
。所有这些双精度值都来自矩形,对吧?图形有一个
drawImage (BufferedImage,int,int,int,int,int,int,int,int,ImageObserver)
方法。这可能就是您正在尝试使用的。您应该改用 int 值。第二个错误表示找不到构造函数
BufferedImage(double, double, int)
。这是一个类似的问题。矩形公开 int 精度字段
x
、y
、height
和width
。你能使用它们吗?例如,rect.x
而不是rect.getX()
The first error says it can't find method
drawImage(BufferedImage,int,int,double,double,double,double,double,double,<nulltype>)
. All those double values are coming from a Rectangle, right?Graphics has a
drawImage(BufferedImage,int,int,int,int,int,int,int,int,ImageObserver)
method. That's probably the one you are trying to use. You should use int values instead.The second error says it can't find constructor
BufferedImage(double, double, int)
. This is a similar problem.Rectangle exposes int precision fields
x
,y
,height
, andwidth
. Can you use them? E.g.,rect.x
instead ofrect.getX()