gpt4 book ai didi

java - 如何复制缓冲图像

转载 作者:行者123 更新时间:2023-12-02 03:56:32 25 4
gpt4 key购买 nike

我编写了以下示例来解决我遇到的问题。当您按下按钮时,controlWhichImage 会切换到 2。问题是,当它从原始图像切换到副本时,图像会消失。

public class PainterDemo01 extends JPanel implements ActionListener {
BufferedImage createdImage;
BufferedImage img;
int controlWhichImage;
JFrame mainFrame;
JButton changePicture;

public PainterDemo01(){
changePicture = new JButton("Press");
changePicture.addActionListener(this);
controlWhichImage = 1;
mainFrame = new JFrame();
mainFrame.add(this);
this.add(changePicture);
mainFrame.setPreferredSize(new Dimension(600,600));
mainFrame.setVisible(true);
mainFrame.pack();
img = loadImage();
}

public BufferedImage loadImage(){
img = null;
try {
img = ImageIO.read(new File("/home/gerry/Desktop/100_0647.JPG"));
} catch (IOException e){
System.out.println("no file here");
}
return img;
}

@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);

loadImage();
if (createdImage == null){
this.createdImage = new BufferedImage(this.getWidth(),this.getHeight(), BufferedImage.TYPE_INT_ARGB);
}

Graphics g2 = this.createdImage.getGraphics();

if (controlWhichImage == 1){
g2.drawImage(img,0,0,img.getWidth(),img.getHeight(),null);
g.drawImage(img, 0,0,img.getWidth(),img.getHeight(),null);
g2.dispose();
}
if (controlWhichImage == 2){
//Draw bufferedImage on to to JPanel
g.drawImage(this.createdImage,this.createdImage.getWidth(),this.createdImage.getHeight(),null);
}
}
@Override
public void actionPerformed(ActionEvent e){
controlWhichImage = 2;
repaint();
}

public static void main(String[] args) {
// TODO code application logic here
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PainterDemo01().setVisible(true);
}
});
}
}

最佳答案

问题是 getGraphics (或者更好的名称 createGraphics)在 if 语句之外被调用,同样对于 2,因此两者都会导致资源泄漏(因为没有调用 g2.dispose),并且也是一个干净的状态。

    if (controlWhichImage == 1) {
Graphics g2 = createdImage.getGraphics();
g2.drawImage(img,0,0,img.getWidth(),img.getHeight(),null);
g2.dispose();
}

还可以执行诸如在绘制代码之外加载图像之类的操作。

关于java - 如何复制缓冲图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35392800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com