JAVA实现图像ROI裁剪
程序员文章站
2022-03-24 19:14:40
...
简介
JAVA实现图片(.jpg)ROI裁剪。
代码实现
package com.hdfs;
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 javaROI {
public static void main(String[] args)
throws IOException {
// TODO Auto-generated method stub
String imPath = "/home/hadoop/Desktop/0001.jpg";
String outPath = "/home/hadoop/Desktop/0001_ROI.jpg";
javaROI roi = new javaROI();
roi.cut(imPath, outPath, 100, 100, 100, 100);
}
public void cut(String imPath, String outPath,
int x, int y, int width, int height)
throws IOException{
FileInputStream is = null;
ImageInputStream iis = null;
try{
//read image
is = new FileInputStream(imPath);
Iterator < ImageReader > it =ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
//image stream
iis = ImageIO.createImageInputStream(is);
reader.setInput(iis, 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, "jpg", new File(outPath));
System.out.println("Saved!");
}finally{
if (is != null ){
is.close();
}
if(iis!=null){
iis.close();
}
}
}
}
下一篇: gif图片