gpt4 book ai didi

java - 写灰度图出错

转载 作者:搜寻专家 更新时间:2023-11-01 03:20:49 25 4
gpt4 key购买 nike

Figure 1 Figure 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();
}
}
}

最佳答案

我不知道你为什么将大数组 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);
}
}

关于java - 写灰度图出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30999208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com