根据坐标裁剪图片

    /**
     * 将单张图片多张内容裁剪
     *
     * @param originalImagePath 原始图像路径
     * @param cutParam          裁剪参数
     */
    public static String cropImage(String originalImagePath, JSONObject cutParam) {
        BufferedImage image = null;
        String fileName, parentPath, suffix;
        try {
            File file = new File(originalImagePath);
            // 文件夹
            parentPath = file.getParent();
            fileName = file.getName();
            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            // 获取文件后缀
            suffix = originalImagePath.substring(originalImagePath.lastIndexOf(".") + 1);
            image = ImageIO.read(new File(originalImagePath));
        } catch (IOException e) {
            throw new MyException(e.getMessage());
        }
        // 左上角X坐标
        Integer leftUpX = cutParam.getInteger("leftUpX");
        // 左上角Y坐标
        Integer leftUpY = cutParam.getInteger("leftUpY");
        // 右下角X坐标
        Integer rightDownX = cutParam.getInteger("rightDownX");
        // 右下角Y坐标
        Integer rightDownY = cutParam.getInteger("rightDownY");

        if (leftUpX >= image.getWidth() || leftUpY >= image.getHeight() ||
                rightDownX > image.getWidth() || rightDownY > image.getHeight()) {
            throw new MyException("Invalid cropping coordinates.");
        }
        // 裁剪后的图像
        BufferedImage subimage = image.getSubimage(leftUpX, leftUpY, rightDownX - leftUpX, rightDownY - leftUpY);
        // 裁剪后的单个文件路径
        String rectanglePath = parentPath + "/" + fileName + "_" + cutParam.getString("index") + "." + suffix;
        File rectangleFile = new File(rectanglePath);
        FileUtil.createDir(rectangleFile.getParent());
        try (ImageOutputStream ios = new FileImageOutputStream(rectangleFile)) {
            ImageIO.write(subimage, suffix, ios);
        } catch (IOException e) {
            throw new MyException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rectanglePath;
    }

测试demo

    public static void main(String[] args) {
        String path = "D:/单图多内容.png";
        JSONObject cutParam = new JSONObject();
        // 左上角X坐标
        cutParam.put("leftUpX", 736);
        // 左上角Y坐标
        cutParam.put("leftUpY", 0);
        // 右下角X坐标
        cutParam.put("rightDownX", 1528);
        // 右下角Y坐标
        cutParam.put("rightDownY", 505);
        cutParam.put("index", 0);
        try {
            cropImage(path, cutParam);
        } catch (Exception e) {

        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dr_eamboat

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值