Carga una imágen, ajusta su tamaño y la guarda como un archivo de imagen jpg permitiendo definir su calidad.

JAVA:
  1. import com.sun.image.codec.jpeg.*;
  2. import java.awt.*;
  3. import java.awt.image.*;
  4. import java.io.*;
  5.  
  6. /**
  7. * Thumbnail.java (requires Java 1.2+)
  8. * Load an image, scale it down and save it as a JPEG file.
  9. * @author Marco Schmidt
  10. */
  11. public class Thumbnail {
  12.   public static void main(String[] args) throws Exception {
  13.     if (args.length != 5) {
  14.       System.err.println("Usage: java Thumbnail INFILE " +
  15.         "OUTFILE WIDTH HEIGHT QUALITY");
  16.       System.exit(1);
  17.     }
  18.     // load image from INFILE
  19.     Image image = Toolkit.getDefaultToolkit().getImage(args[0]);
  20.     MediaTracker mediaTracker = new MediaTracker(new Container());
  21.     mediaTracker.addImage(image, 0);
  22.     mediaTracker.waitForID(0);
  23.     // determine thumbnail size from WIDTH and HEIGHT
  24.     int thumbWidth = Integer.parseInt(args[2]);
  25.     int thumbHeight = Integer.parseInt(args[3]);
  26.     double thumbRatio = (double)thumbWidth / (double)thumbHeight;
  27.     int imageWidth = image.getWidth(null);
  28.     int imageHeight = image.getHeight(null);
  29.     double imageRatio = (double)imageWidth / (double)imageHeight;
  30.     if (thumbRatio <imageRatio) {
  31.       thumbHeight = (int)(thumbWidth / imageRatio);
  32.     } else {
  33.       thumbWidth = (int)(thumbHeight * imageRatio);
  34.     }
  35.     // draw original image to thumbnail image object and
  36.     // scale it to the new size on-the-fly
  37.     BufferedImage thumbImage = new BufferedImage(thumbWidth,
  38.       thumbHeight, BufferedImage.TYPE_INT_RGB);
  39.     Graphics2D graphics2D = thumbImage.createGraphics();
  40.     graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
  41.       RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  42.     graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
  43.     // save thumbnail image to OUTFILE
  44.       FileOutputStream(args[1]));
  45.     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
  46.     JPEGEncodeParam param = encoder.
  47.       getDefaultJPEGEncodeParam(thumbImage);
  48.     int quality = Integer.parseInt(args[4]);
  49.     quality = Math.max(0, Math.min(quality, 100));
  50.     param.setQuality((float)quality / 100.0f, false);
  51.     encoder.setJPEGEncodeParam(param);
  52.     encoder.encode(thumbImage);
  53.     out.close();
  54.     System.out.println("Done.");
  55.     System.exit(0);
  56.   }
  57. }

Popularidad: 35%