【问题标题】:Saving my PNG destroys the alpha channel保存我的 PNG 会破坏 alpha 通道
【发布时间】:2018-10-25 14:38:04
【问题描述】:

我正在尝试使用 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) {
}  

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

【问题讨论】:

    标签: java png alpha


    【解决方案1】:

    通过查看 BufferedImage 类的文档,它不会写入 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;
    

    }

    【讨论】:

    • 谢谢。这正是我做错的,我现在修好了。
    猜你喜欢
    • 1970-01-01
    • 2019-03-18
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    • 2011-10-29
    • 2011-06-06
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多