Java 实现图片去水印处理

思路分析:

遍历整个图片,将图片上某种颜色替换成另一种颜色,默认替换成背景色(背景色取图片左上角第一个像素的颜色)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import org.apache.commons.io.FilenameUtils;

public class ImageTest {

// 图片路径
private static final String imgPath = "D:\\Users\\Admin\\Desktop\\1.png";

// 颜色转换,Key:水印颜色,Value:需要转换成的颜色,null 表示背景色
private static final Map<Color, Color> COLOR_MAP = new HashMap<>();

// 设置转换关系
static {
// COLOR_MAP.put(new Color(255, 204, 204), null);
// COLOR_MAP.put(new Color(245,194,194), new Color(242,242,242));
}

public static void main(String[] args) throws Exception {
File f = new File(imgPath);
BufferedImage bufferedImage = ImageIO.read(f);
int background = bufferedImage.getRGB(0, 0); // 背景色取左上角第一个像素的颜色
for (int x = 0; x < bufferedImage.getWidth(); x++) {
for (int y = 0; y < bufferedImage.getHeight(); y++) {
int rgb = bufferedImage.getRGB(x, y);
for (Entry<Color, Color> colorEntry : COLOR_MAP.entrySet()) {
if (rgb == colorEntry.getKey().getRGB()) {
// 水印替换为背景色
bufferedImage.setRGB(x, y, colorEntry.getValue() == null ? background : colorEntry.getValue().getRGB());
break;
}
}
}
}

// 另存为新图片
String extension = FilenameUtils.getExtension(imgPath);
String newPath = FilenameUtils.getFullPath(imgPath) + FilenameUtils.getBaseName(imgPath) + "_1." + extension;
ImageWriter imageWriter = ImageIO.getImageWritersByFormatName(extension).next();
ImageOutputStream output = ImageIO.createImageOutputStream(new File(newPath));
imageWriter.setOutput(output);
imageWriter.write(bufferedImage);
bufferedImage.flush();
output.flush();
output.close();
}
}