JFrame 不会另存为图像

JFrame won't save as image

我已经搜索了很多,但我仍然无法弄清楚问题出在哪里。图片显示如我所料,但没有保存。

我看过这样的回答:
How to save an Image from a JLabel

保存过程看起来很相似。我什至使用类似的方式下载了一个简单的代码并且它有效。我试过用“paint()”代替“printAll()”,但都不起作用。

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();
            }
        }  
    }
BufferedImage save = new BufferedImage(..., ..., BufferedImage.TYPE_INT_ARGB); 

jpg 文件似乎不喜欢图像类型 ARGB

如果你想要 alpha,那么 png 可以(对我来说)。

如果你想要jpg那么你可以使用RGB的图像类型:

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