本文实例讲述了java实现的图片裁剪功能。分享给大家供大家参考,具体如下:
PicCut.java:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
package Tsets;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
public class PicCut {
public void cut( int x, int y, int width, int height,String srcpath,String subpath) throws IOException { //裁剪方法
FileInputStream is = null ;
ImageInputStream iis = null ;
try {
is = new FileInputStream(srcpath); //读取原始图片
Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName( "jpg" ); //ImageReader声称能够解码指定格式
ImageReader reader = it.next();
iis = ImageIO.createImageInputStream(is); //获取图片流
reader.setInput(iis, true ); //将iis标记为true(只向前搜索)意味着包含在输入源中的图像将只按顺序读取
ImageReadParam param = reader.getDefaultReadParam(); //指定如何在输入时从 Java Image I/O框架的上下文中的流转换一幅图像或一组图像
Rectangle rect = new Rectangle(x, y, width, height); //定义空间中的一个区域
param.setSourceRegion(rect); //提供一个 BufferedImage,将其用作解码像素数据的目标。
BufferedImage bi = reader.read( 0 , param); //读取索引imageIndex指定的对象
ImageIO.write(bi, "jpg" , new File(subpath)); //保存新图片
} finally {
if (is != null )
is.close();
if (iis != null )
iis.close();
}
}
public static void main(String[] args) throws Exception {
PicCut pc = new PicCut();
pc.cut( 20 , 20 , 100 , 100 , "D:\\1.jpg" , "D:\\11.jpg" );
System.out.println( "ok" );
}
}
|
希望本文所述对大家java程序设计有所帮助。