JPG quality when saving out...

edited May 2017 in Share Your Work

I was wondering if this will ever be put in processing. A way to set the quality level on saving jpeg...

I spent an hour or two looking up how to do this. (change the strings if you need) I haven't looked into taking a PImage and well turning it into a BufferedImage This just reads a jpg then saves it out at a different quality

Oh you'll need the following imports

    import javax.imageio.ImageIO;
    import java.awt.image.BufferedImage;
    import java.util.Iterator;
    import javax.imageio.ImageWriter;
    import javax.imageio.ImageWriteParam;
    import javax.imageio.IIOImage;
    //(this can probably simplified to import javax.imageio.*; )

    void saveJpg(float qual)
    {
        // mostly from
        // stackoverflow.com/questions/17108234/setting-jpg-compression-level-with-imageio-in-java
        try{
          File testimage = new File("R:\\john2017.jpg");

          BufferedImage bufimg = ImageIO.read(testimage);
          File outfile = new File("R:\\john2017.jpg");
          Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
          ImageWriter writer = iter.next();
          ImageWriteParam iwp = writer.getDefaultWriteParam();
          iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
          // iwp.setCompressionQuality(0.1f);
          iwp.setCompressionQuality(qual);
          // writer.setOutput(outfile);
          writer.setOutput(ImageIO.createImageOutputStream(outfile));
          writer.write(null, new IIOImage(bufimg, null, null), iwp);
          writer.dispose();
        } catch (IOException ex) {
          System.out.println("Exception : " + ex);
        }
    }

Comments

  • erm that didn't post well at all, well you get the idea! :P

  • edited May 2017

    @rasmussen27 -- is this a question, or is this a solution you developed and want to share under Share Your Work?

  • I should have probably posted it there, I just wondered if there were plans to put something like this into the next version or versions.

  • I think that an added feature is more likely if you open an issue -- and especially if you contribute by making a patch / creating a pull request -- on github:

    In the future if you want to recategorize a post you can edit it and change the category -- don't double-post.

Sign In or Register to comment.