Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save java swing ImageIcon image to file?

Tags:

java

swing

I am using the following code for displaying the Image on the swing frame.

ImageIcon icon = new ImageIcon("image.jpeg");
icon.getImage().flush();
jLabel3.setIcon( icon );

I need a button which when clicked upon will save the image with a jpeg/png extension .

like image 908
sky Avatar asked Feb 03 '26 12:02

sky


1 Answers

I usually do something like this

Image img = icon.getImage();

BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_BYTE_ARGB);

Graphics2D g2 = bi.createGraphics();
g2.drawImage(img, 0, 0, null);
g2.dispose();
ImageIO.write(bi, "jpg", new File("img.jpg"));

also try other image types like BufferedImage.TYPE_INT_RGB, checkout BufferedImage

you may also want to read this Writing/Saving an Image

hope it works for you

like image 164
Leon Avatar answered Feb 05 '26 01:02

Leon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!