Java画像の拡大・縮小

2228 ワード

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("      ");
	}
	
}