0

i would like to know on how to save a image that user selected previously. I only know how to allow user to select image.

This is my current code I have.

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;
    }
CodeName
  • 559
  • 2
  • 6
  • 23

1 Answers1

0

Try this code :

BufferedImage img = ...; 
String location = ...; 
String format = ...; // "PNG" for example
ImageIO.write(img, format, new File(location));
Hele
  • 1,558
  • 4
  • 23
  • 39
  • It's better to use the original bytes of the image file. Using `ImageIO` will often change the (file) size of the image and if JPEG, will likely save it at a different compression/quality level. – Andrew Thompson Feb 02 '15 at 16:41
  • Wouldn't using streams for this task complicate it much? – Hele Feb 02 '15 at 16:44
  • Define 'much'.. BTW - have you tried altering the compression of a JPEG? It isn't rocket science, but not far from it. Check out the `getJpegCompressedImage(BufferedImage image)` method on [this answer](http://stackoverflow.com/a/5998015/418556). And note that there is no way within `ImageIO` to know what compression/quality was used in the original image.. – Andrew Thompson Feb 02 '15 at 16:53
  • "Isn't rocket science"-Yeah, right. I'm going to make an educated guess the OP wants nothing to do with image compression =P – Hele Feb 03 '15 at 03:02
  • Thank you so much! – CodeName Jun 06 '16 at 03:26