简体   繁体   中英

Saving a dynamically created Image to a File.

I have an image, I read the image, add a few things to image (like some text etc).

All this I do inside a JPanel .

Now, I want to save the resulting image to a .png file .

I think, there is a way to do this for a buffered image using ImageIO.write()

But I cannot convert the dynamically created image to a BufferedImage.

Is there a way I can go about this ?

You can use the Screen Image class.

It will create a BufferedImage of your JPanel. The class also has code to write the image to a file.

All this I do inside a JPanel .

Do it instead in another BufferedImage displayed in a JLabel . The code can get a Graphics2D object using BufferedImage.createGraphics() method. Paint the image and text to the new Graphics2D instance and you then the new image can be saved directly, along with changes.

Use Following method it worked for me...

void TakeSnapShot(JPanel panel,String Locatefile){  
           BufferedImage bi = new BufferedImage(panel.getSize().width,  panel.getSize().height,BufferedImage.TYPE_INT_RGB);  

           panel.paint(bi.createGraphics()); 

           File image = new File(Locatefile);  
        try{  
            image.createNewFile();  
            ImageIO.write(bi, "png", image);
        }catch(Exception ex){  
        }  
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM