Java图片裁剪工具类

此工具类用于裁剪图片

@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();
        }
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值