【问题标题】:Error in writing the grayscale image写灰度图出错
【发布时间】:2015-06-23 20:41:44
【问题描述】:

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

【问题讨论】:

    标签: java image-processing


    【解决方案1】:

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

    【讨论】:

    • @Fast Snail Superrr....我得到了图像。再次感谢。但是为什么前面的代码失败了?有什么想法...?
    猜你喜欢
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    相关资源
    最近更新 更多