代码
package com.ekkcole.controlle.抠图;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class KouTu {
public static int color_range = 120;
public static void main(String[] args) throws IOException {
long start = System.currentTimeMillis();
BufferedImage image = ImageIO.read(new File("C:\\Users\\ron\\Desktop\\测试图\\16410394627191873.png"));
int height = image.getHeight();
int width = image.getWidth();
ImageIcon imageIcon = new ImageIcon(image);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
g2D.drawImage(imageIcon.getImage(), 0, 0, null);
int alpha = 0;
for (int y = bufferedImage.getMinY(); y < bufferedImage.getHeight(); y++) {
for (int x = bufferedImage.getMinX(); x < bufferedImage.getWidth(); x++) {
int rgb = bufferedImage.getRGB(x, y);
if (colorInRange(rgb)) {
alpha = 0;
} else {
alpha = 255;
}
rgb = (alpha << 24) | (rgb & 0x00ffffff);
bufferedImage.setRGB(x, y, rgb);
}
}
g2D.drawImage(bufferedImage, 0, 0, null);
ImageIO.write(bufferedImage, "png", new File("C:\\Users\\ron\\Desktop\\测试图\\16410394627191873(1).png"));
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start) + "毫秒");
System.out.println("抠图成功");
}
public static boolean colorInRange(int color) {
int red = (color & 0xff0000) >> 16;
int green = (color & 0x00ff00) >> 8;
int blue = (color & 0x0000ff);
System.out.println("red+ = " + red + ",green+ = " + green + ",blue+ = " + blue);
if (red >= color_range && green >= color_range && blue >= color_range) {
return true;
}
return false;
}
}
![请添加图片描述](https://img-blog.csdnimg.cn/e8e77d4409284275aebc81df068537ef.png)