保存我的 PNG 会破坏 alpha 通道

Saving my PNG destroys the alpha channel

我试图保存带有 alpha 通道的 PNG 图像,但在进行了一些像素明智的操作并保存之后,alpha 通道在每个像素上都回到了 255。这是我的代码:

首先是像素操作:

public BufferedImage apply(BufferedImage image) {
    int pixel;

    for (int y = 0; y < image.getHeight(); y++) {
        for (int x = 0; x < image.getWidth(); x++) {
            pixel = image.getRGB(x, y);

            if (threshold < getAverageRGBfromPixel(pixel)) {
                image.setRGB(x, y, new Color(0f, 0f, 0f, 0f).getRGB());
            }               
        }
    }


    return image;
}

注意:应该透明的像素是黑色的,所以我肯定会打它们。

这是保存代码。

@Test
public void testGrayscaleFilter() {
    ThresholdFilter thresholdFilter = new ThresholdFilter();

    testImage = thresholdFilter.apply(testImage);

    File outputFile = new File(TEST_DIR + "/testGrayPicture" + ".png");

    try {
        // retrieve image
        ImageIO.write(testImage, "png", outputFile);
    } catch (IOException e) {
}  

谁能告诉我我做错了什么?

通过查看 BufferedImage 的文档 class,它不会写入 alpha 通道的唯一原因是原始 BufferedImage 对象的类型为 TYPE_INT_RGB 而不是 TYPE_INT_ARGB.

一个解决方案是创建一个具有相同高度和宽度但类型为 TYPE_INT_ARGB 的新 BufferedImage 对象,当您更改像素数据时,使用 else 语句复制它。

public BufferedImage apply(BufferedImage image) {
int pixel;
BufferedImage newImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);

for (int y = 0; y < image.getHeight(); y++) {
    for (int x = 0; x < image.getWidth(); x++) {
        pixel = image.getRGB(x, y);

        if (threshold < getAverageRGBfromPixel(pixel)) {
            newImage.setRGB(x, y, new Color(0f, 0f, 0f, 0f).getRGB());
        }
        else {
            // Not sure about this line
            newImage.setRGB(x, y, pixel);
        }
    }
}


return image;

}