1 package com.knowgate.misc; 2 3 import com.knowgate.debug.*; 4 import com.knowgate.misc.Gadgets; 5 import com.sun.image.codec.jpeg.*; 6 import java.awt.*; 7 import java.awt.image.*; 8 import java.io.*; 9 import javax.imageio.*; 10 import java.net.*; 11 import javax.servlet.*; 12 13 18 19 public class Thumbnail { 20 23 public static synchronized void getThumb(String sInFile, ServletOutputStream sOutputStream, String sWidth, String sHeight, String sQuality) throws Exception { 24 System.setProperty("java.awt.headless","true"); 25 if (DebugFile.trace) 26 DebugFile.writeln("BEGIN getThumb"); 27 Image image = Toolkit.getDefaultToolkit().getImage(sInFile); 29 if (DebugFile.trace) 30 DebugFile.writeln("Image created"); 31 32 MediaTracker mediaTracker = new MediaTracker(new Frame()); 33 mediaTracker.addImage(image, 0); 34 mediaTracker.waitForID(0); 35 36 if (DebugFile.trace) 37 DebugFile.writeln("Image loaded"); 38 39 int thumbWidth = Integer.parseInt(sWidth); 41 int thumbHeight = Integer.parseInt(sHeight); 42 double thumbRatio = (double)thumbWidth / (double)thumbHeight; 43 int imageWidth = image.getWidth(null); 44 int imageHeight = image.getHeight(null); 45 double imageRatio = (double)imageWidth / (double)imageHeight; 46 if (thumbRatio < imageRatio) { 47 thumbHeight = (int)(thumbWidth / imageRatio); 48 } else { 49 thumbWidth = (int)(thumbHeight * imageRatio); 50 } 51 52 if (DebugFile.trace) 53 DebugFile.writeln("Image resized"); 54 55 BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB); 58 Graphics2D graphics2D = thumbImage.createGraphics(); 59 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 60 RenderingHints.VALUE_INTERPOLATION_BILINEAR); 61 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 62 63 if (DebugFile.trace) 64 DebugFile.writeln("graphics2D created"); 65 66 String sOutFile = Gadgets.generateUUID() + ".tmp"; 68 ServletOutputStream out = sOutputStream; 69 JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); 70 JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage); 71 int quality = Integer.parseInt(sQuality); 72 quality = Math.max(0, Math.min(quality, 100)); 73 param.setQuality((float)quality / 100.0f, false); 74 encoder.setJPEGEncodeParam(param); 75 encoder.encode(thumbImage); 76 77 if (DebugFile.trace) 78 DebugFile.writeln("Encode ended"); 79 } 80 } 81 82 | Popular Tags |