技术分享 — Java如何实现证件照换底色

在这里插入图片描述

demo体验

https://www.coderutil.com/rgb

证件找换底色是我的智能简历下(https://www.coderutil.com/jianlibot)的一个小功能,技术实现上走了不少弯路,简单做个技术分享。

实现思路

图片是由一个个像素块组成的,每个像素块对应一个RGB颜色值。将照片加载到内存,转换成一个二维的RGB矩阵,想办法识别到边缘的背景色,遍历二维矩阵,将跟背景色相同的颜色值替换为目标颜色值(如:蓝色背景 更换为 白色背景)

快快上代码

talk is cheap, show me the code:

// 比较邪乎了,为啥是30,不是20,其实20也可以,就是一个优化参数
private static final int critical = 30;


/***
 * 处理图片背景色
 * @param path 原图地址
 * @param targetRgb 目标颜色RGB值 16进制颜色码
 * @param isNetWork 原图是否为网络图片地址
 * @return
 */
public static BufferedImage handleBufferImageBackgroundRGB(String path, int targetRgb, boolean isNetWork) throws Exception {
    File file;
    if (isNetWork) {
        // 处理网络图片,先将图片下载到本地(上传的头像)
        file = FileUtil.downloadNetWorkFile(path);
    } else {
        file = new File(path);
    }
    /**
     * 用来处理图片的缓冲流
     */
    BufferedImage bi = null;
    try {
        /**
         * 用ImageIO将图片读入到缓冲中
         */
        bi = ImageIO.read(file);
    } catch (Exception e) {
        log.error("图像加载内存失败", e);
    }

    /**
     * 得到图片的长宽
     */
    int width = bi.getWidth();
    int height = bi.getHeight();
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    /**
     * 获取左上角颜色,默认左上角像素块颜色为背景色
     */
    int pixel = bi.getRGB(critical, critical);
    log.info("图片名称:{}, targetRgb:{}, width:{}, height:{}, pixel:{}",
            file.getName(), targetRgb, width, height, pixel);

    /**
     * 这里是遍历图片的像素,因为要处理图片的背色,所以要把指定像素上的颜色换成目标颜色
     * 这里 是一个二层循环,遍历长和宽上的每个像素
     */
    Graphics g = image.getGraphics();
    for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
            /**
             * 得到指定像素(i,j)上的RGB值,
             */
            int nowPixel = bi.getRGB(x, y);
            /**
             * 进行换色操作,我这里是要把蓝底换成白底,那么就判断图片中rgb值是否在蓝色范围的像素
             */
            // 核心代码:但是这样会有误差,还需要优化边缘、人像边框
            int p = pixel == nowPixel ? targetRgb : nowPixel;
            g.setColor(new Color(p));
            g.fillRect(x, y, 1, 1);
        }
    }
    log.info("处理完毕:{}",file.getName());
    return image;
}

完了,代码一上,没东西可写了,看效果吧!!!!

效果展示

蓝色背景换白色背景:

更换前

在这里插入图片描述

更换后

在这里插入图片描述

原文:https://www.coderutil.com/article?id=107

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员盒子应用作者

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

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

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

打赏作者

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

抵扣说明:

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

余额充值