(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.blogjava.net/zhyiwww
|----------------------------------------------------------------------------------------|
posted on 2007-10-18 17:54
zhyiwww 阅读(1361)
评论(4) 编辑 收藏 所属分类:
java basic