/**
* 去除图片背景色,图片透明化
* @param image 原始图片
* @param isCompress 是否压缩
* @param imageWidth 压缩后的图片宽度: isCompress为true时不能为null
* @param imageHeight 他所后的图片高度: isCompress为true时不能为null
*/
public static BufferedImage clearImageBackground(BufferedImage image, boolean isCompress, Integer imageWidth, Integer imageHeight) throws IOException {
BufferedImage bufferedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_ARGB);
try {
image = transImageBackgroundColor(image, Color.BLACK, Color.WHITE);
if(isCompress){
image = resizeImage(image, imageWidth, imageHeight);
}
bufferedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
int width = image.getWidth();
int height = image.getHeight();
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
int rgba = image.getRGB(x, y);
if (isWhite(rgba)) {
bufferedImage.setRGB(x, y, 0x00ffff);
} else {
bufferedImage.setRGB(x, y, rgba);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return bufferedImage;
}
public static boolean isWhite(int rgba) {
int r = (rgba >> 16) & 0xFF;
int g = (rgba >> 8) & 0xFF;
int b = rgba & 0xFF;
return r > 250 && g > 250 && b > 250;
}
修改图片背景
/**
* 压缩图片
* @param image 原始图片
* @param filterColor 过滤的颜色(如:文字黑色不替换,则filterColor为BLACK)
* @param color 新的背景颜色
*/
public static BufferedImage transImageBackgroundColor(BufferedImage image, Color filterColor, Color color) {
for (int x = image.getMinX(); x < image.getWidth(); x++) {
for (int y = image.getMinY(); y < image.getHeight(); y++) {
int rgb = image.getRGB(x, y);
Color src = new Color(rgb);
if(filterColor.equals(src)){
image.setRGB(x, y, src.getRGB());
continue;
}
image.setRGB(x, y, color.getRGB());
}
}
return image;
}