首页

通过java.awt.Image/Graphics2D定义ThumbnailGenerator缩略图生成器工具类可以生成大图的等比例缩放小图代码示例

标签:java.awt.Image,Graphics2D,ThumbnailGenerator,缩略图工具类,生成缩略图,图片生成器,等比例图     发布时间:2018-07-30   

一、前言

基于java.awt.Graphics2D、java.awt.Image画图类定义ThumbnailGenerator缩略图生成器工具类,用于将任意大图片缩放等比例缩略图片操作,详情参见下面代码示例。

二、代码示例

package com.xwood.util;@b@@b@import java.awt.Color;@b@import java.awt.Graphics2D;@b@import java.awt.Image;@b@import java.awt.RenderingHints;@b@import java.awt.image.BufferedImage;@b@import java.io.File;@b@@b@public class ThumbnailGenerator {@b@	@b@	/**@b@	 * 执行生成图片缩略图@b@	 * @param origImglFile 原始图片路径@b@	 * @param targetImgFile 转换后图片路径@b@	 * @param thumbWidth 转换后width@b@	 * @param thumbHeight 转换后高度@b@	 * @throws Exception@b@	 */@b@	public static void invoke(String origImglFile, String targetImgFile, int thumbWidth, int thumbHeight) throws Exception{@b@		@b@		Image image = javax.imageio.ImageIO.read(new File(origImglFile));@b@	    @b@	    double thumbRatio = (double)thumbWidth / (double)thumbHeight;@b@	    int imageWidth    = image.getWidth(null);@b@	    int imageHeight   = image.getHeight(null);@b@	    double imageRatio = (double)imageWidth / (double)imageHeight;@b@	    if (thumbRatio < imageRatio) @b@	    {@b@	    	thumbHeight = (int)(thumbWidth / imageRatio);@b@	    } @b@	    else @b@	    {@b@	      	thumbWidth = (int)(thumbHeight * imageRatio);@b@	    }@b@	    @b@		if(imageWidth < thumbWidth && imageHeight < thumbHeight)@b@		{@b@			thumbWidth = imageWidth;@b@			thumbHeight = imageHeight;@b@		}@b@		else if(imageWidth < thumbWidth)@b@			thumbWidth = imageWidth;@b@		else if(imageHeight < thumbHeight)@b@			thumbHeight = imageHeight;@b@@b@	    BufferedImage thumbImage = new BufferedImage(thumbWidth, thumbHeight, BufferedImage.TYPE_INT_RGB);@b@	    Graphics2D graphics2D = thumbImage.createGraphics();@b@	    graphics2D.setBackground(Color.WHITE);@b@    	graphics2D.setPaint(Color.WHITE); @b@    	graphics2D.fillRect(0, 0, thumbWidth, thumbHeight);@b@	    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);@b@	    graphics2D.drawImage(image, 0, 0, thumbWidth, thumbHeight, null);@b@	    @b@		javax.imageio.ImageIO.write(thumbImage, "JPG", new File(targetImgFile));@b@	}@b@	@b@	public  static  void  main(String[] args)  throws Exception{@b@		invoke("C:/Users/nijun/Pictures/test/orignalImg.jpg","C:/Users/nijun/Pictures/test/targetImg.jpg",150,84);@b@	}@b@}

执行后结果如下图(将3264*1836大图生成149*84同比例小图)

通过java.awt.Image/Graphics2D定义ThumbnailGenerator缩略图生成器工具类可以生成大图的等比例缩放小图代码示例