Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 保存我的PNG会破坏alpha通道_Java_Png_Alpha - Fatal编程技术网

Java 保存我的PNG会破坏alpha通道

Java 保存我的PNG会破坏alpha通道,java,png,alpha,Java,Png,Alpha,我试图用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++) {

我试图用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;
}

有人能告诉我我做错了什么吗?

通过查看BuffereImage类的文档,它不会写入alpha通道的唯一原因是原始BuffereImage对象的类型是\u INT\u RGB而不是\u INT\u ARGB

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

公共缓冲区映像应用(缓冲区映像){
整数像素;
BuffereImage newImage=新的BuffereImage(image.getWidth(),image.getHeight(),buffereImage.TYPE_INT_ARGB);
对于(int y=0;y

}

谢谢。那正是我做错的,我现在把它修好了。
@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) {
}