通过java代码将一个表情包的背景替换为空白或者透明
以下代码都是通过 ai生成的,已测试好用。
java">import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**/*** @Author xiaoli* @Date 2025/2/24 10:12* @Version 1.0*/
public class Image {public static void main(String[] args) {// 使用示例replaceBackground(new File("C:\\Users\\Lee\\Desktop\\哈士奇.png"),new File("C:\\Users\\Lee\\Desktop\\哈士奇透明.png"),true, // true表示透明,false表示白色50 // 颜色阈值(0-255));}/*** 替换图片背景* @param inputFile 输入图片文件* @param outputFile 输出图片文件(建议PNG格式)* @param toTransparent true=替换为透明,false=替换为白色* @param colorThreshold 颜色识别阈值(小于该值视为黑色)*/public static void replaceBackground(File inputFile, File outputFile,boolean toTransparent, int colorThreshold) {try {// 读取原始图片BufferedImage originalImage = ImageIO.read(inputFile);// 创建支持透明的新图片BufferedImage newImage = new BufferedImage(originalImage.getWidth(),originalImage.getHeight(),BufferedImage.TYPE_INT_ARGB);// 遍历每个像素for (int y = 0; y < originalImage.getHeight(); y++) {for (int x = 0; x < originalImage.getWidth(); x++) {int pixel = originalImage.getRGB(x, y);// 提取RGB颜色分量int red = (pixel >> 16) & 0xFF;int green = (pixel >> 8) & 0xFF;int blue = pixel & 0xFF;// 判断是否为背景色(黑色或接近黑色)if (red <= colorThreshold&& green <= colorThreshold&& blue <= colorThreshold) {if (toTransparent) {// 设置为透明newImage.setRGB(x, y, 0x00FFFFFF);} else {// 设置为白色(不透明)newImage.setRGB(x, y, 0xFFFFFFFF);}} else {// 保留原始像素(带透明度)newImage.setRGB(x, y, pixel);}}}// 保存处理后的图片(建议使用PNG格式保持透明度)ImageIO.write(newImage, "PNG", outputFile);} catch (IOException e) {e.printStackTrace();}}
}