java裁剪图片

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
* 对图片做裁剪
*/
public class ImageUtils {
    /**
	 * 对图片做裁剪
	 * @param input 源图片
	 * @param input 保存的图片
	 * @param sourceType 源图片的类型
	 * @param savedType 保存图片的类型
	 * @param x x坐标
	 * @param y y坐标
	 * @param width 宽度
	 * @param height 高度
	*/
    public static void cutImage(InputStream input, OutputStream out, 
			String sourceType, String savedType, 
			int x, int y, int width, int height) 
			throws IOException {
        ImageInputStream imageStream = null;
        try {
			//根据指定的类型创建ImageReader
            Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(sourceType);
            ImageReader reader = readers.next();
			//把需要裁剪的图片读到内存中
            imageStream = ImageIO.createImageInputStream(input);
            reader.setInput(imageStream, true);
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle(x, y, width, height);
            param.setSourceRegion(rect);
            BufferedImage bi = reader.read(0, param);
			//保存裁剪完的图片
            ImageIO.write(bi, savedType, out);
        } finally {
            imageStream.close();
        }
    }

    
    public static void main(String[] args) throws Exception {
        ImageUtils.cutImage(new FileInputStream("c:\\test.bmp"),
                  new FileOutputStream("c:\\1111cut.jpg"), 
				  "bmp", 
				  "jpg", 
				  0, 
				  0, 
				  100, 
				  36);
    }
}

 

你可能感兴趣的:(java图片裁剪)