灰度图像写入错误。

4

图1 图2

以下是我编写的代码,用于更改灰度图像的像素值以创建全白图像(所有像素值均设置为255)。但是,我没有得到完全白色的图像,而是在中间得到了黑色的垂直条纹,如图2所示。我错在哪里了?

package dct;

import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.ImageIO;

public class writeGScale {
    public static void main(String[] args){
        File file = new File("bridge.jpg");
        BufferedImage img = null;
        try{
            img = ImageIO.read(file);
        }
        catch(Exception e){
            e.printStackTrace();
        }

        int width = img.getWidth();
        int height = img.getHeight();
        int[] tempArr = new int[width*height];

        WritableRaster raster1=img.getRaster();

        for(int i=0;i<width;i++){
            for(int j=0;j<height;j++){
                tempArr[0] = 255;
                raster1.setPixel(i, j, tempArr);
            }
        }

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
        image.setData(raster1);

        try{
            File ouptut = new File("change.png");
            ImageIO.write(image, "png", ouptut);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
1个回答

2

我不知道为什么你要将大数组 tempArr = new int[width*height] 传递给 setpixel 方法。我创建了一个代表白色的 int 数组 col,并将其传递给 setPixel() 方法,然后我就能够得到完全白色的图像输出。

int col[]={255,255,255};

WritableRaster raster1=img.getRaster();

for(int i=0;i<width;i++)
{
    for(int j=0;j<height;j++)
    {
        raster1.setPixel(i, j, col);
    }
} 

1
@快速蜗牛,太棒了...我收到图片了。再次感谢。但是为什么之前的代码失败了?有任何想法吗...? - Rohit S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接