【问题标题】:How to Delete the white pixels in an image in java如何在java中删除图像中的白色像素
【发布时间】:2014-07-21 17:53:53
【问题描述】:

如何在将图像加载到Panel 之前删除图像的白色像素
panel中加载图片的方法是:

public  void ajouterImage(File fichierImage) {   
    // desiiner une image à l'ecran 
    try {
        monImage = ImageIO.read(fichierImage);
    } catch (IOException e) {
        e.printStackTrace();
    }
    repaint(); 
}  

【问题讨论】:

  • 您无法从图像中“移除”像素。你的意思是把它们改成另一种颜色,比如黑色?
  • 你想让它透明吗?
  • 我想在面板中加载图像但没有白色像素,因为我使用的是黑白图片,我想在面板中只显示黑色像素
  • 当我让它透明时,它们不会在面板中占用空间?
  • 我要选择要在面板中显示的签名者

标签: java


【解决方案1】:

你不能从图像中移除一个像素,但你肯定可以改变它的颜色,甚至让它透明。

假设您在某处有一个像素数组作为变量,您可以将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 位。不错。
  • 但是在面板中图像没有完全显示只有一半,我该怎么做才能显示签名者?例如,我可以用鼠标移动面板中的图像???我该怎么做??
【解决方案2】:

假设通过删除像素意味着将它们设置为透明,则需要将图像的 alpha 值设置为零。这是一个函数colorToAlpha(BufferedImage, Color),它将BufferedImageColor 作为输入并返回另一个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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 2015-03-02
    • 2010-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多