JAVA 判断图片是否存在透明区域

该博客介绍了两种检测图片是否透明的方法:一种是从前端上传图片文件,另一种是通过图片URL。在 ImgUtil.java 中,定义了一个静态方法 isTransparent 来检查 BufferedImage 对象中是否存在透明像素。通过对每个像素的 RGB 值进行检查,如果 alpha 通道为0,则判断图片为透明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一: 前端传图片文件

 	@PostMapping("/check_is_opaque")
    public Result checkImgIsOpaque(@RequestParam(value = "file") MultipartFile file) {
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = Thumbnails.of(file.getInputStream()).size(600, 600).outputQuality(0.8).asBufferedImage();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtil.success(ImageUtil.isTransparent(bufferedImage));
    }

二:引用图片路径

 @PostMapping("/check_is_opaque")
    public Result checkImgIsOpaque(@RequestParam("url") String url) {
        boolean isTransparent = false;
        try {
            isTransparent = ImageUtil.isTransparent(Thumbnails.of(url).asBufferedImage());
        } catch (IOException e) {
            log.error("检测图片是否透明出错 了", e);
        }
        return ResultUtil.success(!isTransparent);
    }

ImgUtil.java

public class ImageUtil {
    public static boolean isTransparent(BufferedImage bufImg) {
        int height = bufImg.getHeight();
        int width = bufImg.getWidth();
        boolean isTransparent = false;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                int pixel = bufImg.getRGB(i, j);
                if (pixel >> 24 == 0) {
                    isTransparent = true;
                    break;
                }
            }
        }
        return isTransparent;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值