java如何将图像数据复制到BuffereImage的子类中?
我有一个叫做位图的类,它是从BuffereImage扩展而来的
public class Bitmap extends BufferedImage {...
它的一个名为copyImage的方法将内容从源图像复制到类中,虽然有效,但该方法无法保持源图像的原始纵横比和尺寸
public void copyImage(Image image) {
if (image != null) {
BufferedImage bi = (BufferedImage) image;
Graphics g = getGraphics();
g.drawImage(bi, 0, 0, width, height, null);
}
}
我希望此方法将源图像复制到类中,并保持其原始纵横比和尺寸,我考虑调整宽度和高度,我将上面的代码修改为:
public void copyImage(Image image) {
if (image != null) {
this.width = image.getWidth(null);
this.height = image.getWidth(null);
BufferedImage bi = (BufferedImage) image;
Graphics g = getGraphics();
g.drawImage(bi, 0, 0, width, height, null);
}
}
但是它不起作用,我如何修改上面的代码来复制图像? 提前谢谢
# 1 楼答案
这是错误的:
你的主要问题是:
this
图像,您不应该这样做,也不应该这样做this.height = image.getWidth(null);
将参数图像的宽度指定给this.height
字段其他问题:
应该是这样
使用显示概念证明的MCVE测试代码:
如果运行此代码,您将看到3个图像在3个JOptionPanes中显示为ImageIcon,第一个是原始的空白MyImage对象,然后在第一次世界大战中的2个图像被复制到原始图像中之后