I am generating high quality thumbnail in java for that I am using java-image-scaling High quality image scaling library which is provided under Change license to The BSD 3-Clause License
For running this program you have to include java-image-scaling-0.8.6.jar and Filter.jar
This is example to generate thumbnail with maintaining aspect ratio
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | import com.mortennobel.imagescaling.AdvancedResizeOp; import com.mortennobel.imagescaling.ResampleOp; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Image; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.imageio.ImageIO; public class Test { public static void main(String[] args) throws IOException, Exception { Test tt = new Test(); String sourceImagePath = "D:\\tt.jpg"; String destinationPath = "D:\\tt1"; String smallPath = "D:\\tt2"; int pos = sourceImagePath.lastIndexOf("."); String imgFormat = sourceImagePath.substring(pos + 1); String thumbnailImage = destinationPath.concat(".").concat(imgFormat); String smallImg = smallPath.concat(".").concat(imgFormat); tt.getThumbnail(sourceImagePath, thumbnailImage, imgFormat, 500, 400); tt.getThumbnail(sourceImagePath, smallImg, imgFormat, 50, 50); } public void getThumbnail(String sourceImage, String thumbnailImage, String imgFormat, int picWidth, int picHeight) throws Exception { System.out.println(sourceImage + " " + thumbnailImage + " " + picWidth + " " + picHeight); Image image = javax.imageio.ImageIO.read(new File(sourceImage)); double thumbRatio = (double) picWidth / (double) picHeight; int imageWidth = image.getWidth(null); int imageHeight = image.getHeight(null); double imageRatio = (double) imageWidth / (double) imageHeight; if (thumbRatio < imageRatio) { picHeight = (int) (picWidth / imageRatio); } else { picWidth = (int) (picHeight * imageRatio); } if ((imageWidth < picWidth) && (imageHeight < picHeight)) { picWidth = imageWidth; picHeight = imageHeight; } else if (imageWidth < picWidth) { picWidth = imageWidth; } else if (imageHeight < picHeight) { picHeight = imageHeight; } File f = new File(sourceImage); BufferedImage src = ImageIO.read(f); ResampleOp resampleOp = new ResampleOp(picWidth, picHeight); resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Soft); BufferedImage rescaled = resampleOp.filter(src, null); ImageIO.write(rescaled, imgFormat, new File(thumbnailImage)); } } |