01: package org.claros.intouch.webdisk.models;
02:
03: import java.awt.Container;
04: import java.awt.Graphics2D;
05: import java.awt.Image;
06: import java.awt.MediaTracker;
07: import java.awt.RenderingHints;
08: import java.awt.Toolkit;
09: import java.awt.image.BufferedImage;
10: import java.io.ByteArrayOutputStream;
11:
12: import com.sun.image.codec.jpeg.JPEGCodec;
13: import com.sun.image.codec.jpeg.JPEGEncodeParam;
14: import com.sun.image.codec.jpeg.JPEGImageEncoder;
15:
16: public class Thumbnail {
17: public byte[] getThumb(String fileName, int thumbWidth,
18: int thumbHeight) throws Exception {
19: Image image = Toolkit.getDefaultToolkit().getImage(fileName);
20: MediaTracker mediaTracker = new MediaTracker(new Container());
21: mediaTracker.addImage(image, 0);
22: mediaTracker.waitForID(0);
23:
24: double thumbRatio = (double) thumbWidth / (double) thumbHeight;
25: int imageWidth = image.getWidth(null);
26: int imageHeight = image.getHeight(null);
27: double imageRatio = (double) imageWidth / (double) imageHeight;
28: if (thumbRatio < imageRatio) {
29: thumbHeight = (int) (thumbWidth / imageRatio);
30: } else {
31: thumbWidth = (int) (thumbHeight * imageRatio);
32: }
33: // draw original image to thumbnail image object and
34: // scale it to the new size on-the-fly
35: BufferedImage thumbImage = new BufferedImage(thumbWidth,
36: thumbHeight, BufferedImage.TYPE_INT_RGB);
37: Graphics2D graphics2D = thumbImage.createGraphics();
38: graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
39: RenderingHints.VALUE_INTERPOLATION_BILINEAR);
40: graphics2D
41: .drawImage(image, 0, 0, thumbWidth, thumbHeight, null);
42: // save thumbnail a byte array
43: ByteArrayOutputStream out = new ByteArrayOutputStream();
44: JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
45: JPEGEncodeParam param = encoder
46: .getDefaultJPEGEncodeParam(thumbImage);
47: int quality = 100;
48: quality = Math.max(0, Math.min(quality, 100));
49: param.setQuality((float) quality / 100.0f, false);
50: encoder.setJPEGEncodeParam(param);
51: encoder.encode(thumbImage);
52: out.close();
53: return out.toByteArray();
54: }
55: }
|