java实现图片裁剪

  • 引言

在日常开发中,偶尔会遇到产品提出要求“图片裁剪”,对于这种需求那可是一头雾水啊,以前光记得crud了,现在突然来了个大活。

  • 举个栗子

需求:我们只裁剪下半段照片

java实现图片裁剪_第1张图片

  • How to do

1.提前引入包

        
        
            org.bytedeco
            javacv-platform
            1.5.3
        
        
        
            cn.hutool
            hutool-all
            5.4.4
        

 2.逻辑实现

    public static void main(String[] args) throws IOException, InterruptedException {
        String sourceFile = "C:/Users/Administrator/Desktop/我妹妹的照片.png";
        String targetFile = "C:/Users/Administrator/Desktop/我妹妹的照片(裁下半段).png";
        File file = new File(sourceFile);
        BufferedImage sourceImage = ImageIO.read(file);
        Rectangle rectangle = new Rectangle();
//        x,y其实就是坐标,能确定一个点位,指的是从那个点位开始截取,x0y0代表的是从左下角点开始裁剪
        rectangle.x = 0;
        rectangle.y = 0;
//        宽度不变,直接获取原图片宽度
        rectangle.width = sourceImage.getWidth(null);
//        高度裁一半
        rectangle.height = sourceImage.getHeight(null) / 2;
//        开始截取,返回一个image对象
        Image image = ImgUtil.cut(sourceImage, rectangle);
//        转字节数组并输出到文件
        byte[] bytes = ImgUtil.toBytes(image, "png");
        FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
        fileOutputStream.write(bytes);
        fileOutputStream.close();
    }

成功了

java实现图片裁剪_第2张图片

你可能感兴趣的:(java,python,前端)