1 回答

TA貢獻1813條經驗 獲得超2個贊
這是錯誤的:
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);
}
}
你的主要問題是:
您似乎正在嘗試更改原始圖像的固有寬度和高度,
this
圖像,您不應該這樣做,而不是這樣您正在將參數圖像的寬度分配給
this.height
字段this.height = image.getWidth(null);
其他事宜:
你沒有節省資源
你正在制作危險且不必要的演員表
它應該是
public void copyImage(Image image) {
if (image != null) {
// don't change the width/height of your original image
int width = image.getWidth(null);
// int height = image.getWidth(null);
int height = image.getHeight(null); // *** Note change ***
// BufferedImage bi = (BufferedImage) image; // *** no need ***
Graphics g = getGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose(); // save resources
}
}
使用顯示概念證明的MCVE測試代碼:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class TestImage {
public static final String SOMME_PATH = "https://upload.wikimedia.org/"
+ "wikipedia/commons/thumb/f/fa/Cheshire_Regiment_trench_Somme_1916.jpg"
+ "/1024px-Cheshire_Regiment_trench_Somme_1916.jpg";
public static final String BATTLE_PATH = "https://upload.wikimedia.org/wikipedia/"
+ "commons/1/13/K%C3%A4mpfe_auf_dem_Doberdo.JPG";
public static void main(String[] args) {
int imgW = 1000;
int imgH = 700;
MyImage myImage = new MyImage(imgW, imgH, BufferedImage.TYPE_INT_ARGB);
BufferedImage sommeTrench = null;
BufferedImage battleOfDoberdò = null;
try {
URL url = new URL(SOMME_PATH);
sommeTrench = ImageIO.read(url);
url = new URL(BATTLE_PATH);
battleOfDoberdò = ImageIO.read(url);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
Icon icon = new ImageIcon(myImage);
JOptionPane.showMessageDialog(null, icon, "Original MyImage", JOptionPane.PLAIN_MESSAGE);
myImage.copyImage(sommeTrench);
icon = new ImageIcon(myImage);
JOptionPane.showMessageDialog(null, icon, "MyImage with Somme Trench", JOptionPane.PLAIN_MESSAGE);
myImage.copyImage(battleOfDoberdò);
icon = new ImageIcon(myImage);
JOptionPane.showMessageDialog(null, icon, "MyImage with Battle Of Doberdò", JOptionPane.PLAIN_MESSAGE);
}
}
class MyImage extends BufferedImage {
public MyImage(int width, int height, int imageType) {
super(width, height, imageType);
}
public void copyImage(Image image) {
if (image != null) {
int width = image.getWidth(null);
int height = image.getHeight(null); // *** Note change ***
Graphics g = getGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose(); // save resources
}
}
}
如果您運行此代碼,您將看到 3 個圖像在 3 個 JOptionPanes 中顯示為 ImageIcons,第一個是原始空白 MyImage 對象,然后在第一次世界大戰中的 2 個圖像被復制到原始圖像中。
添加回答
舉報