1. 程式人生 > >20個非常有用的JAVA程式片段

20個非常有用的JAVA程式片段

  1. private void createThumbnail(String filename, int thumbWidth, int thumbHeight, int quality, String outFilename)    
  2.     throws InterruptedException, FileNotFoundException, IOException    
  3. {    
  4.     // load image from filename    
  5.     Image image = Toolkit.getDefaultToolkit().getImage(filename);    
  6.     MediaTracker mediaTracker = new MediaTracker(new Container());    
  7.     mediaTracker.addImage(image, 0);    
  8.     mediaTracker.waitForID(0);    
  9.     // use this to test for errors at this point: System.out.println(mediaTracker.isErrorAny());    
  10.     // determine thumbnail size from WIDTH and HEIGHT    
  11.     double thumbRatio = (double)thumbWidth / (double)thumbHeight;    
  12.     int imageWidth = image.getWidth(null);    
  13.     int imageHeight = image.getHeight(null);    
  14.     double imageRatio = (double)imageWidth / (double)imageHeight;    
  15.     if (thumbRatio < imageRatio) {    
  16.         thumbHeight = (int)(thumbWidth / imageRatio);    
  17.     } else {    
  18.         thumbWidth = (int)(thumbHeight * imageRatio);    
  19.     }    
  20.     // draw original image to thumbnail image object and    
  21.     // scale it to the new size on-the-fly    
  22.     BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);    
  23.     Graphics2D graphics2D = thumbImage.createGraphics();    
  24.     graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);    
  25.     graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);    
  26.     // save thumbnail image to outFilename    
  27.     BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename));    
  28.     JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);    
  29.     JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);    
  30.     quality = Math.max(0, Math.min(quality, 100));    
  31.     param.setQuality((float)quality / 100.0f, false);    
  32.     encoder.setJPEGEncodeParam(param);    
  33.     encoder.encode(thumbImage);    
  34.     out.close();    
  35. }