简体   繁体   中英

loss of image parts while setting pixel values to 0 and 1 from grayscale in java

i am doing work on images using java. i read a gray scale image and convert the pixel values to 0 and 1 i got the output image correctly for only some images. in others some image portions are lost here is the code i am using to make the image array back into image

`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..");`

size of the image is same as original but the entire size contains only a portion of original image.can u help me

Your problem is probably related to the sample model you are using. The sample model is responsible to describe how the Raster is going to store the data, maybe you are using a model that puts more info per pixel and then the image gets only a part of the original buffer.

Cheers

[Update] @Joop Egen is correct you need to use the sample model from the image in which you defined that you are using a grayscale byte per pixel "configuration"

got a gud answer for my problem it worked well for all images(including 24 bit and 8 bit images)

 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);` 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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