简体   繁体   中英

JPEG encoder - set quality from command line

I'm building a JPEG image encoder. As it stands, in order to encode an image the user enters the name of the file they wish to encode and name of the file to be created as a result.

I'd like the user to be able to set the quality of the encoding in the command line. I tried renaming the second argument (100) in new JpegEncoder(image, 100, new FileOutputStream(args[1])); encoder.Compress(); new JpegEncoder(image, 100, new FileOutputStream(args[1])); encoder.Compress(); to args[2] but that didn't work.

public class JPGencoder {

  public static void main ( String[] args ) {
  String[] names = ImageIO.getWriterFormatNames();
  BufferedImage image = null;
  JpegEncoder encoder = null; 

  try {
     image = ImageIO.read( new File( args[0] ) );
      System.err.println("Process image " + args[0]);
      System.err.println(image.toString());
  } catch (Exception e) { 
      System.err.println("Problems with image " + args[0]);
  }

  try {
     encoder = new JpegEncoder(image, 100, new FileOutputStream(args[1]));
     encoder.Compress();
  } catch (Exception e) {
      System.out.println("well that didn't work");
  }

} }

Based on this definition of JpegEncoder the second argument to the JpegEncode constructor is an int .

The type of args[2] is a String so presumably by " did not work " you mean " did not compile ". To convert args[2] to an int :

Integer.parseInt(args[2]);

This will throw a NumberFormatException if args[2] is not a valid int .

It is not difficult to set the JPG compression/quality using ImageIO . Here are some snippets that might get you started.

private ImageWriteParam imageWriterParams;
private ImageWriter imageWriter;
File out = new File("some.jpg");
// ...

Iterator it = ImageIO.getImageWritersBySuffix("jpg");
// presume every iterator has precisely 1 writer
imageWriter = (ImageWriter)it.next();
imageWriterParams = imageWriter.getDefaultWriteParam();
if ( imageWriterParams.canWriteCompressed() ) {
    try {
        imageWriterParams.setCompressionMode( ImageWriteParam.MODE_EXPLICIT );
    } catch(Exception e) {
        e.printStackTrace();
    }
} else {
    logger.log(Level.WARNING, "ImageWriter cannot compress!");
}
imageWriterParams.setCompressionQuality(qualF);

FileImageOutputStream fios = new FileImageOutputStream(out);
imageWriter.setOutput(fios);
imageWriter.write(
    null,
    new IIOImage(image,null,null),
    imageWriterParams );
fios.flush();
fios.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM