Search code examples
javaswingjlabelgraphics2djavax.imageio

JFrame won't save as image


I've search a lot, but yet i still can't figure out where's the issue. The image display as i expected but it doesn't save it.

I've watch answers like this:
https://stackoverflow.com/questions/12575201/how-to-save-a-image-on-jframe\ How to save an Image from a JLabel

Looks very similar the save process. I even download a simple code using a similar way and it works. i've tried with "paint()" instead of "printAll()" and don't work neither.

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class BorderImage extends JFrame {
    
    public static void main(String[] args){ 
        try {
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            JFileChooser fc = new JFileChooser();
            
            if(fc.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION){
                BufferedImage img = ImageIO.read(fc.getSelectedFile());
                JLabel label = new JLabel(new ImageIcon(img), JLabel.CENTER);
                
                int w = img.getWidth();
                int h = img.getHeight();
                if (w > h) {
                    int diff = (w - h)/2;
                    frame.getContentPane().setBackground(Color.BLACK);
                    frame.setSize(w, w);
                } else if (h > w) {
                    frame.getContentPane().setBackground(Color.BLACK);
                    frame.setSize(h, h);
                }       
                
                frame.getContentPane().add(label);
                frame.setVisible(true);
                
                try {
                    BufferedImage save = new BufferedImage(frame.getWidth(),
                            frame.getHeight(), BufferedImage.TYPE_INT_ARGB);    
                    Graphics2D graphics = save.createGraphics();                
                    frame.printAll(graphics);               
                    graphics.dispose(); 
                    ImageIO.write(save, "jpg", new File("newImage.jpg"));
                    
                    } catch (IOException x) {
                        x.printStackTrace();
                        }
                }  
            } catch(IOException e) {
                e.printStackTrace();
            }
        }  
    }

Solution

  • BufferedImage save = new BufferedImage(..., ..., BufferedImage.TYPE_INT_ARGB); 
    

    It appears that jpg files don't like the image type ARGB.

    If you want the alpha then png works (for me).

    It you want jpg then you can use an image type of RGB:

    BufferedImage save = new BufferedImage(..., ..., BufferedImage.TYPE_INT_RGB);