1 4 5 package org.objectweb.jac.util; 6 7 import java.awt.Frame ; 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.ByteArrayOutputStream ; 15 import java.io.OutputStream ; 16 import javax.imageio.ImageIO ; 17 18 22 23 public class Thumbnail { 24 25 37 public static byte[] createThumbArray(byte[] data, 38 int thumbWidth, int thumbHeight, 39 int quality) 40 throws Exception 41 { 42 ByteArrayOutputStream result = new ByteArrayOutputStream (); 43 createThumb(data,thumbWidth,thumbHeight,quality,result); 44 return result.toByteArray(); 45 } 46 47 59 public static void createThumb(byte[] data, 60 int thumbWidth, int thumbHeight, 61 int quality, 62 OutputStream out) 63 throws Exception 64 { 65 Image image = Toolkit.getDefaultToolkit().createImage(data); 66 MediaTracker mediaTracker = new MediaTracker (new Frame ()); 67 int trackID = 0; 68 mediaTracker.addImage(image,trackID); 69 mediaTracker.waitForID(trackID); 70 if (image.getWidth(null)<=thumbWidth && 71 image.getHeight(null)<=thumbHeight) 72 out.write(data); 73 else 74 createThumb(image,thumbWidth,thumbHeight,quality,out); 75 } 76 77 90 public static void createThumb(Image image, 91 int thumbWidth, int thumbHeight, 92 int quality, 93 OutputStream out) 94 throws Exception 95 { 96 int imageWidth = image.getWidth(null); 97 int imageHeight = image.getHeight(null); 98 double thumbRatio = (double)thumbWidth / (double)thumbHeight; 99 double imageRatio = (double)imageWidth / (double)imageHeight; 100 if (thumbRatio < imageRatio) { 101 thumbHeight = (int)(thumbWidth / imageRatio); 102 } else { 103 thumbWidth = (int)(thumbHeight * imageRatio); 104 } 105 BufferedImage thumbImage = 108 new BufferedImage (thumbWidth, 109 thumbHeight, BufferedImage.TYPE_INT_RGB); 110 Graphics2D graphics2D = thumbImage.createGraphics(); 111 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 112 RenderingHints.VALUE_INTERPOLATION_BILINEAR); 113 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 114 ImageIO.write(thumbImage,"jpeg",out); 116 } 117 } 118 119 | Popular Tags |