当前位置: 首页 > 工具软件 > IM_Java > 使用案例 >

Java使用ImageMagick+Im4Java裁剪图片

乐正锦
2023-12-01

一、背景

BufferedImage是将图片整个加载到内存中的,而图片又比较大,可能有多个线程在转,所以会有内存溢出的问题。因而使用ImageMagick+Im4Java去裁剪图片

二、需求

将图片裁剪为16:9的比例

三、实现

1、获取图片的长和宽

public static void main(String[] args) throws Exception {
        Iterator<ImageReader> iterator = ImageIO.getImageReadersByFormatName("png");
        ImageReader reader = iterator.next();

        File file = new File("C:\\Users\\jie10.gao\\Pictures\\513698797896.png");
        FileInputStream in = new FileInputStream(file);
        ImageInputStream imageInputStream = ImageIO.createImageInputStream(in);
        reader.setInput(imageInputStream, true);

        int w, h;
        int width = reader.getWidth(0);
        int height = reader.getHeight(0);
        float fw = (float) width;
        float fh = (float) height;
        float number = fw / fh;
        if (number > (16.0 / 9)) {
            w = height * 16 / 9;
            h = height;
        } else {
            w = width;
            h = width * 9 / 16;
        }
        cutImage("C:\\Users\\jie10.gao\\Pictures\\513698797896.png", "D:\\newPicture.png", (width - w) / 2, (height - h) / 2, w, h);
    }

2、开始裁剪

//ImageMagick的安装路径
public static String imageMagicPath = "C:\\Program Files\\ImageMagick-7.1.0-Q16-HDRI";

    public static void cutImage(String imagePath, String newPath, int x, int y, int width, int height)
            throws Exception {

        IMOperation op = new IMOperation();
        op.addImage(imagePath);
        /** width:裁剪的宽度 * height:裁剪的高度 * x:裁剪的横坐标 * y:裁剪纵坐标 */
        op.crop(width, height, x, y);
        op.addImage(newPath);
        ConvertCmd convert = new ConvertCmd();
        convert.setSearchPath(imageMagicPath);
        convert.run(op);

    }

 类似资料: