Java 图片缩放

package zf.model.dom4j;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.File;

import javax.imageio.ImageIO;

public class ImageTest {
	
	/**
	 * 缩放图片
	 * @param source		源图片
	 * @param tartetW		缩放后的宽度
	 * @param targetH	    缩放后的高度
	 * @return
	 */
	public static BufferedImage resize(BufferedImage source , int tartetW , int targetH	 ){
		double sw = source.getWidth();	//源图片宽度
		double sh = source.getHeight();	//源图片高度
		double w = tartetW / sw ;	//得到缩放宽度比例
		double h = tartetW / sh ; 	//得到缩放高度比例
		BufferedImage target = null ;
		int type = source.getType();	//得到图像颜色类型
		if(type == BufferedImage.TYPE_CUSTOM){	//如果是自定义图像
			ColorModel cm = source.getColorModel();
			WritableRaster raster = cm.createCompatibleWritableRaster(tartetW	, targetH);
			boolean alpha = cm.isAlphaPremultiplied();
			target = new BufferedImage(cm , raster , alpha , null);
		}else{
			target = new BufferedImage(tartetW , targetH , type);
			Graphics2D g = target.createGraphics();
			g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
			g.drawRenderedImage(source	, AffineTransform.getScaleInstance(w, h));
			g.dispose();
		}
		return target;
	}
	
	/**
	 * 保存图片
	 * @param formImageStr
	 * @param saveToImageStr
	 * @param width
	 * @param height
	 */
	public void saveImageAsJpg(String fromImageStr , String saveToImageStr , int width  , int height) throws Exception{
		BufferedImage srcImg = null ;
		String imgType = "JPEG";
		if(fromImageStr.toUpperCase().endsWith(".PNG"))
			imgType = "PNG";
		File saveFile = new File(saveToImageStr);
		File fromFile = new File(fromImageStr);
		srcImg = ImageIO.read(fromFile);
		if(width > 0 && height > 0){
			srcImg = resize(srcImg, width, height );
		}
		ImageIO.write(srcImg, imgType, saveFile);
	}
	
	public static void main(String[] args) throws Exception {
		ImageTest it = new ImageTest();
		it.saveImageAsJpg("f:/s.jpg", "f:/x.jpg",100 , 100 );
		System.out.println("图片缩放完成");
	}
	
}

你可能感兴趣的:(Java 图片缩放)