JFrame不会另存为图像

问题描述

我已经搜索了很多,但是我仍然不知道问题出在哪里。图像显示与我预期的一样,但没有保存。

我看到了这样的答案:
https://stackoverflow.com/questions/12575201/how-to-save-a-image-on-jframe\ 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); 

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...