繁体   English   中英

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

[英]Convert an image to a 2D array and then get the image back in Java

我想将图像转换为2D像素阵列,对其进行一些操作,然后将生成的2D阵列转换回图像。 但是我总是得到纯黑色的图像。 我无法弄清楚哪里出了问题。 这是我正在做的所有操作都需要在8位灰度图像上完成。

  • 首先,我得到2D像素数组。

     public int[][] compute(File file) { try { BufferedImage img= ImageIO.read(file); Raster raster=img.getData(); int w=raster.getWidth(),h=raster.getHeight(); int pixels[][]=new int[w][h]; for (int x=0;x<w;x++) { for(int y=0;y<h;y++) { pixels[x][y]=raster.getSample(x,y,0); } } return pixels; } catch (Exception e) { e.printStackTrace(); } return null; } 
  • 然后我对像素数组进行一些操作

  • 接下来,我将数组转换回图像。

     public java.awt.Image getImage(int pixels[][]) { int w=pixels.length; int h=pixels[0].length; BufferedImage image=new BufferedImage(w,h,BufferedImage.TYPE_BYTE_GRAY); WritableRaster raster=(WritableRaster)image.getData(); for(int i=0;i<w;i++) { for(int j=0;j<h;j++) { raster.setSample(i,j,0,pixels[i][j]); } } File output=new File("check.jpg"); try { ImageIO.write(image,"jpg",output); } catch (Exception e) { e.printStackTrace(); } return image; } 

但是我得到了完整的黑色图像,并且我确定它不是完整的黑色。 我应该怎么做才能得到正确的结果?

编辑 -应用efan的解决方案后,当我将图像保存到文件中时,假设(0,0)的像素值为68,然后在计算同一文件中的像素值时,有时会更改为70,有时会更改为71。每个像素的失真很小,但是会破坏整个图像。 有什么解决办法吗?

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

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不能完全选择您需要的内容。 有所不同可能会更好,但是我不知道这些类型与颜色/样本模型的对应程度如何。 如果知道所需的样本模型,则可以使用它:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM