且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将图像转换为2D数组,然后用Java重新获得图像

更新时间:2022-11-09 23:32:45

我认为图像完全为黑色的原因是 Raster SampleModel 是错误的.这是我对您的代码所做的:

I think the reason image is completely black is that SampleModel for Raster is wrong. Here is what i did with your code:

private SampleModel sampleModel;

public int[][] compute(File file)
{
    ...
    sampleModel = raster.getSampleModel();
    ...
}

public java.awt.Image getImage(int pixels[][])
{
    ...
    WritableRaster raster= Raster.createWritableRaster(sampleModel, new Point(0,0));
    for(int i=0;i<w;i++)
    {
        for(int j=0;j<h;j++)
        {
            raster.setSample(i,j,0,pixels[i][j]);
        }
    }

    BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY);
    image.setData(raster);
    ...
}

这对我来说很好.我的理解是 BufferedImage.TYPE_BYTE_GRAY 不能完全选择您所需要的.有所不同可能会更好,但我不知道这些类型与颜色/样本模型的对应程度如何.而且,如果您知道需要哪种示例模型,则可以使用它:

And this worked for me fine. My understanding is that BufferedImage.TYPE_BYTE_GRAY does not select exactly what you need. Something different might work better, but i don't know how exactly those types correspond to color/sample model. And if you know which sample model you need you can just use it:

WritableRaster raster= Raster.createWritableRaster(new PixelInterleavedSampleModel(0, w, h, 1, 1920, new int[] {0}), new Point(0,0));