(zhyiwww@163.com? 轉載請注明出處 作者:zhyiwww )
最近,有兩個朋友在問我關于圖片裁剪的問題,不過以前的代碼找不到了,所以,就把完整的例子又整理了一下。可以實現在一個完整的圖片上,根據需要,定位想要截取的圖片的左上角的坐標和圖片的大小,就可以取得該圖片。
完整的實現代碼如下:
package org.zy.app;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.util.Iterator;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import javax.imageio.ImageReader;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
/**
?* @author zhangyi
?* date : 2007-10-18
?*/
public class SplitImage {
??? /**
??? ?* ????????? ?? ImageReader
??? ?*
??? ?* @param imgPath
??? ?* @throws IOException
??? ?*/
??? public void readImage() throws IOException {
??? ??? // get JPEG image reader iterator
??? ??? Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
??? ??? System.out.println(readers);
??? ???
??? ??? // get image reader
??? ??? ImageReader reader = (ImageReader) readers.next();
??? ??? System.out.println(reader);
??? ??? // get original image input stream
??? ??? InputStream source = this.getClass().getResourceAsStream("img01.jpg");
??? ??? System.out.println("image input source is : " + source);
??? ???
??? ??? // get ImageInputStream of the image to split
??? ??? ImageInputStream iis = ImageIO.createImageInputStream(source);
??? ??? reader.setInput(iis, true);
??? ???
??? ??? // the image param
??? ??? ImageReadParam param = reader.getDefaultReadParam();
??? ??? int imageIndex = 0;
//??? ???
//??? ??? int half_width = reader.getWidth(imageIndex) / 2;
//??? ??? int half_height = reader.getHeight(imageIndex) / 2;
??? ??? // the coordinate and the size on the image that you want to split on
??? ??? Rectangle rect = new Rectangle(300, 490, 200, 100);
??? ??? param.setSourceRegion(rect);
??? ???
??? ??? BufferedImage bi = reader.read(0, param);
??? ???
??? ??? // write the split picture
??? ??? ImageIO.write(bi, "jpg", this.initDestFile());
??? }
??? public File initDestFile() throws IOException {
??? ??? File f = new File("c:\\img02.jpg");
??? ??? if (f.exists()) {
??? ??? ??? f.delete();
??? ??? }
??? ??? f.createNewFile();
??? ??? return f;
??? }
??? public static void main(String[] args) {
??? ??? SplitImage si = new SplitImage();
??? ??? try {
??? ??? ??? si.readImage();
??? ??? } catch (IOException e) {
??? ??? ??? System.out.println("exception");
??? ??? }
??? }
}
代碼下載
SplitImage這只是一個簡單的實現。當然,也可以在servlet端來實現此功能。
|----------------------------------------------------------------------------------------|
版權聲明 版權所有 @zhyiwww
引用請注明來源 http://www.tkk7.com/zhyiwww
|----------------------------------------------------------------------------------------|
posted on 2007-10-18 17:54
zhyiwww 閱讀(1369)
評論(4) 編輯 收藏 所屬分類:
java basic