如何保存用户选择并保存到桌面文件夹中的图像

时间:2015-02-02 15:56:23

标签: java image swing jfilechooser filechooser

我想知道如何保存用户之前选择的图像。我只知道如何让用户选择图像。

这是我目前的代码。

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        JFileChooser chooser = new JFileChooser();
        chooser.showOpenDialog(null);
        File f = chooser.getSelectedFile();
        // String filename = f.getAbsolutePath();
        //jTextField1.setText(filename);
        try {
            ImageIcon ii=new ImageIcon(scaleImage(120, 120, ImageIO.read(new File(f.getAbsolutePath()))));//get the image from file chooser and scale it to match JLabel size
            jLabel3.setIcon(ii);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static BufferedImage scaleImage(int w, int h, BufferedImage img) throws Exception {
        BufferedImage bi;
        bi = new BufferedImage(w, h, BufferedImage.TRANSLUCENT);
        Graphics2D g2d = (Graphics2D) bi.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY));
        g2d.drawImage(img, 0, 0, w, h, null);
        g2d.dispose();
        return bi;
    }

1 个答案:

答案 0 :(得分:0)

试试这段代码:

BufferedImage img = ...; 
String location = ...; 
String format = ...; // "PNG" for example
ImageIO.write(img, format, new File(location));