https://www.coderutil.com/rgb
证件找换底色是我的智能简历下(https://www.coderutil.com/jianli)的一个小功能,技术实现上走了不少弯路,简单做个技术分享。
实现思路图片是由一个个像素块组成的,每个像素块对应一个RGB颜色值。将照片加载到内存,转换成一个二维的RGB矩阵,想办法识别到边缘的背景色,遍历二维矩阵,将跟背景色相同的颜色值替换为目标颜色值(如:蓝色背景 更换为 白色背景)
快快上代码talk is cheap, show me the code:
// 比较邪乎了,为啥是30,不是20,其实20也可以,就是一个优化参数
private static final int critical = 30;
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 {
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++) {
int nowPixel = bi.getRGB(x, y);
// 核心代码:但是这样会有误差,还需要优化边缘、人像边框
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



