印章之类的抠图 把最多相似的颜色设置为透明颜色
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class ImageUtil {
public static boolean localImgToAlpha(File file, String path) {
try {
// 读取输入图片文件
BufferedImage inputImage = ImageIO.read(new FileInputStream(file));
// 创建新的带有透明度通道的BufferedImage
BufferedImage alphaImage = new BufferedImage(inputImage.getWidth(), inputImage.getHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2D = alphaImage.createGraphics();
// 将输入图片绘制到带有透明度通道的图片上
g2D.drawImage(inputImage, 0, 0, null);
g2D.dispose();
for (int y = 0; y < alphaImage.getHeight(); y++) {
for (int x = 0; x < alphaImage.getWidth(); x++) {
int rgb = alphaImage.getRGB(x, y);
int red = (rgb & 0xFF0000) >> 16;
int green = (rgb & 0xFF00) >> 8;
int blue = rgb & 0xFF;
// 检查像素是否接近白色或灰色
if ((255 - red) < 30 && (255 - green) < 30 && (255 - blue) < 30) {
// 将透明度通道设置为0(透明)
rgb = 0x00FFFFFF & rgb; // 将RGB值的最高8位(透明度通道)设置为0
}
alphaImage.setRGB(x, y, rgb);
}
}
// 将带有透明度的图片保存为PNG文件到指定路径
ImageIO.write(alphaImage, "png", new File(path));
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}