1 package test; 2 3 6 7 import java.awt.Container ; 8 import java.awt.Graphics2D ; 9 import java.awt.Image ; 10 import java.awt.MediaTracker ; 11 import java.awt.RenderingHints ; 12 import java.awt.Toolkit ; 13 import java.awt.image.BufferedImage ; 14 import java.io.BufferedOutputStream ; 15 import java.io.FileOutputStream ; 16 17 import com.sun.image.codec.jpeg.JPEGCodec; 18 import com.sun.image.codec.jpeg.JPEGEncodeParam; 19 import com.sun.image.codec.jpeg.JPEGImageEncoder; 20 21 public class Thumbnail 22 { 23 24 public static void main(String [] args) throws Exception 25 { 26 if (args.length != 5) 27 { 28 System.err.println("Usage: java Thumbnail INFILE " 29 + "OUTFILE WIDTH HEIGHT QUALITY"); 30 System.exit(1); 31 } 32 Image image = Toolkit.getDefaultToolkit().getImage(args[0]); 34 MediaTracker mediaTracker = new MediaTracker (new Container ()); 35 mediaTracker.addImage(image, 0); 36 mediaTracker.waitForID(0); 37 int thumbWidth = Integer.parseInt(args[2]); 39 int thumbHeight = Integer.parseInt(args[3]); 40 double thumbRatio = (double) thumbWidth / (double) thumbHeight; 41 int imageWidth = image.getWidth(null); 42 int imageHeight = image.getHeight(null); 43 double imageRatio = (double) imageWidth / (double) imageHeight; 44 if (thumbRatio < imageRatio) 45 { 46 thumbHeight = (int) (thumbWidth / imageRatio); 47 } 48 else 49 { 50 thumbWidth = (int) (thumbHeight * imageRatio); 51 } 52 BufferedImage thumbImage = new BufferedImage (thumbWidth, thumbHeight, 55 BufferedImage.TYPE_INT_RGB); 56 Graphics2D graphics2D = thumbImage.createGraphics(); 57 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 58 RenderingHints.VALUE_INTERPOLATION_BILINEAR); 59 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 60 BufferedOutputStream out = new BufferedOutputStream ( 62 new FileOutputStream (args[1])); 63 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 64 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); 65 int quality = Integer.parseInt(args[4]); 66 quality = Math.max(0, Math.min(quality, 100)); 67 param.setQuality((float) quality / 100.0f, false); 68 encoder.setJPEGEncodeParam(param); 69 encoder.encode(thumbImage); 70 System.out.println("Done."); 71 System.exit(0); 72 } 73 } | Popular Tags |