[英]How to Delete the white pixels in an image in 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值。 像素数组将被称为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
作为输入并返回另一个BufferedImage
与Color
设置为透明的。
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<pixels.length;i++)
{
if (pixels[i] == remove.getRGB())
{
pixels[i] = 0x00ffffff;
}
}
image.setRGB(0, 0, WIDTH, HEIGHT, pixels, 0, WIDTH);
return image;
}
用法示例:
BufferedImage processed = colorToAlpha(rawImage, Color.WHITE)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.