在java中将像素值设置为灰度等级时,丢失图像部分

时间:2013-12-24 20:45:06

标签: java image bufferedimage

我正在使用java进行图像处理。 我读取灰度图像并将像素值转换为0和1我只为一些图像正确获得了输出图像。 在其他人中,一些图像部分丢失了 这是我用来使图像阵列回到图像的代码

`BufferedImage I = ImageIO.read(new File("path"));
 SampleModel sampleModel;
 Raster pixelData;
 pixelData = I.getData();
 int[][] pixels=new int[wid][hgt];
 sampleModel=pixelData.getSampleModel();



 BufferedImage image=new BufferedImage(wid,hgt,BufferedImage.TYPE_BYTE_BINARY);
 WritableRaster raster=Raster.createWritableRaster(sampleModel,new Point(0,0));
     for(int i=0;i<wid;i++)
     {
         for(int j=0;j<hgt;j++)
         {
            raster.setSample(i,j,0,pixels[i][j]);
         }
     }
     image.setData(raster);

File output=new File("path");
    ImageIO.write(image,"png",output);
 System.out.println("..End..");`

图像的大小与原始大小相同,但整个大小只包含原始图像的一部分。大家帮帮我

2 个答案:

答案 0 :(得分:1)

您的问题可能与您使用的样本模型有关。样本模型负责描述Raster如何存储数据,也许您正在使用一个模型,每个像素放置更多信息,然后图像只获得原始缓冲区的一部分。

干杯

[更新] @Joop Egen是正确的,您需要使用您定义的图像中的样本模型,即每个像素使用灰度字节“配置”

答案 1 :(得分:0)

我的问题得到了一个很好的答案,它适用于所有图像(包括24位和8位图像)

 BufferedImage I = ImageIO.read(new File("path"));
 Raster pixelData;
 pixelData = I.getData();
 int pixels[][]=new int[wid][hgt];


     for ( x=0;x<wid;x++)
     {
         for( y=0;y<hgt;y++)
         {
             pixels[x][y]=pixelData.getSample(x,y,0);
          }  
     }


 BufferedImage image=new BufferedImage(wid,hgt,BufferedImage.TYPE_BYTE_BINARY);
 ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
 int[] nBits = { 8 };
 ColorModel cm = new ComponentColorModel(cs, nBits, false, true,Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
 SampleModel sm = cm.createCompatibleSampleModel(wid, hgt);
 WritableRaster raster=Raster.createWritableRaster(sm,new Point(0,0));
     for(int i=0;i<wid;i++)
     {
         for(int j1=0;j1<hgt;j1++)
         {
            raster.setSample(i,j1,0,pixels[i][j1]);
         }
     }
  image.setData(raster);
  File output=new File("path");
  ImageIO.write(image,"png",output);` 
相关问题