How to copy bufferedImage

后端 未结 4 888
迷失自我
迷失自我 2021-01-28 02:48

I have written the following example to give something runnable of a problem I am having. When you press the button the controlWhichImage switches to 2. The problem is that when

相关标签:
4条回答
  • 2021-01-28 03:19

    Use img obj since its already instantiated but not createdImage obj, createdImage contains null since its just declared but not instantiated. If you use createdImage obj means if you perform any operation upon createdImage obj then you will get NullPointerException.

    Graphics g2 = this.img.getGraphics();
    ---------
    
    0 讨论(0)
  • 2021-01-28 03:25

    Of course! You have to go and paint the image at the outskirts. Please use this

    g.drawImage(this.createdImage, 0, 0, this.createdImage.getWidth(),this.createdImage.getHeight(),null);
    
    0 讨论(0)
  • 2021-01-28 03:32

    The problem is that getGraphics (or better named createGraphics) is called outside the if statement, also for 2, hence both causing a resource leak (as no g2.dispose is called), and also a clean slate.

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

    Also do things like loading the image outside the paint code.

    0 讨论(0)
  • 2021-01-28 03:43

    See this question if you want to know how to copy an BufferedImage: How to copy BufferedImage

    0 讨论(0)
提交回复
热议问题