此工具类用于裁剪图片
@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class CutImageUtil {
// 源图片路径名称
private String srcpath ;
// 剪切图片存放路径名称
private String subpath ;
// 剪切点坐标
private int x ;
private int y ;
private int width ;
private int height ;
public CutImageUtil(int x, int y, int width, int height) {
this .x = x ;
this .y = y ;
this .width = width ;
this .height = height ;
}
/**
* 对图片裁剪,并把裁剪完的新图片保存 。
*/
public boolean cut()throws IOException {
FileInputStream is = null ;
ImageInputStream iis = null ;
try {
// 读取图片文件
is =new FileInputStream(srcpath);
// 声明解码格式
Iterator<ImageReader> it= ImageIO.getImageReadersByFormatName("jpg");
ImageReader reader = it.next();
// 获取图片流
iis = ImageIO.createImageInputStream(is);
reader.setInput(iis, true ) ;
ImageReadParam param = reader.getDefaultReadParam();
// 指定坐标空间中的一个区域
Rectangle rect = new Rectangle(x, y, width, height);
// 提供一个 BufferedImage,将其用作解码像素数据的目标。
param.setSourceRegion(rect);
BufferedImage bi=reader.read(0,param);
// 保存新图片
ImageIO.write(bi,"jpg",new File(subpath));
return true;
} catch (IOException e){
log.info("图片裁剪失败,失败原因:"+e.getMessage());
return false;
// e.printStackTrace();
} finally {
if (is != null){
is.close();
}
if (iis != null){
iis.close();
}
}
}
public static boolean cutImage(int x, int y, int w, int h, String oldUrl, String newUrl) {
CutImageUtil cutImage = new CutImageUtil(x, y, w, h);
log.info(MessageFormat.format("裁剪的坐标位置大小x:{0},y:{1},w:{2},h:{3}",x,y,w,h));
cutImage.srcpath = oldUrl; // 旧图路径
cutImage.subpath = newUrl; // 裁剪后路径
try {
return cutImage.cut();
} catch (IOException e) {
log.info("图片裁剪失败,失败原因:"+e.getMessage());
return false;
// e.printStackTrace();
}
}
}