写灰度图出错
Error in writing the grayscale image
以下是我编写的代码,用于更改灰度图像的像素值以创建全白图像(所有像素值设置为 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);
}
}
以下是我编写的代码,用于更改灰度图像的像素值以创建全白图像(所有像素值设置为 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);
}
}