如何在java中删除图像中的白色像素
如何在将图像加载到Panel
之前删除图像的白色像素
在面板中加载图像的方法是:
public void ajouterImage(File fichierImage) { // desiiner une image à l'ecran try { monImage = ImageIO.read(fichierImage); } catch (IOException e) { e.printStackTrace(); } repaint(); }
您无法从图像中删除像素,但您确定可以更改它的颜色,甚至可以使其透明。
假设您在某处将像素数组作为变量,并且可以为其指定BufferedImage
的RGB值。 像素arrays将被称为pixels
:
try { monImage = ImageIO.read(fichierImage); int width = monImage.getWidth(); int height = monImage.getHeight(); pixels = new int[width * height]; image.getRGB(0, 0, width, height, pixels, 0, width); for (int i = 0; i < pixels.length; i++) { // I used capital F's to indicate that it's the alpha value. if (pixels[i] == 0xFFffffff) { // We'll set the alpha value to 0 for to make it fully transparent. pixels[i] = 0x00ffffff; } } } catch (IOException e) { e.printStackTrace(); }
假设通过删除像素意味着将它们设置为透明,则需要将图像的alpha值设置为零。 这是一个函数colorToAlpha(BufferedImage, Color)
,它将BufferedImage
和Color
作为输入,并返回另一个将Color
设置为透明的BufferedImage
。
public static BufferedImage colorToAlpha(BufferedImage raw, Color remove) { int WIDTH = raw.getWidth(); int HEIGHT = raw.getHeight(); BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB); int pixels[]=new int[WIDTH*HEIGHT]; raw.getRGB(0, 0, WIDTH, HEIGHT, pixels, 0, WIDTH); for(int i=0; i
用法示例:
BufferedImage processed = colorToAlpha(rawImage, Color.WHITE)