1 package de.jwi.jgallery.imageio; 2 3 24 25 import java.awt.Graphics2D ; 26 import java.awt.Image ; 27 import java.awt.RenderingHints ; 28 import java.awt.image.BufferedImage ; 29 import java.io.File ; 30 import java.io.IOException ; 31 import java.io.Serializable ; 32 import java.util.Iterator ; 33 34 import javax.imageio.ImageIO ; 35 import javax.imageio.ImageWriteParam ; 36 import javax.imageio.ImageWriter ; 37 import javax.imageio.stream.ImageOutputStream ; 38 39 import de.jwi.jgallery.IThumbnailWriter; 40 41 45 public class ImageIOThumbnailWriter 46 implements IThumbnailWriter, Serializable 47 { 48 public void write(File infile, File outfile, float compressionQuality, 49 int thumbBounds) throws IOException 50 { 51 Image image = ImageIO.read(infile); 53 54 int imageWidth = image.getWidth(null); 55 int imageHeight = image.getHeight(null); 56 57 float thumbRatio = (float) thumbBounds 58 / Math.max(imageWidth, imageHeight); 59 60 int thumbWidth = (int) (imageWidth * thumbRatio); 61 int thumbHeight = (int) (imageHeight * thumbRatio); 62 63 BufferedImage thumbImage = new BufferedImage (thumbWidth, thumbHeight, 66 BufferedImage.TYPE_INT_RGB); 67 Graphics2D graphics2D = thumbImage.createGraphics(); 68 graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, 69 RenderingHints.VALUE_INTERPOLATION_BICUBIC); 70 graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null); 71 72 ImageWriter writer = null; 74 Iterator iter = ImageIO.getImageWritersByFormatName("jpg"); 75 if (iter.hasNext()) 76 { 77 writer = (ImageWriter ) iter.next(); 78 } 79 80 ImageWriteParam iwp = writer.getDefaultWriteParam(); 81 iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 82 iwp.setCompressionQuality(compressionQuality); 83 84 ImageOutputStream ios = ImageIO.createImageOutputStream(outfile); 86 writer.setOutput(ios); 87 88 writer.write(thumbImage); 89 90 ios.flush(); 92 writer.dispose(); 93 ios.close(); 94 } 95 96 } 97 | Popular Tags |