Misalignement in the output Bitmap created from a byte array

Posted by Daniel on Stack Overflow See other posts from Stack Overflow or by Daniel
Published on 2012-09-12T15:36:27Z Indexed on 2012/09/12 15:38 UTC
Read the original article Hit count: 332

Filed under:

I am trying to understand why I have troubles creating a Bitmap from a byte array. I post this after a careful scrutiny of the existing posts about Bitmap creation from byte arrays, like the followings:

Creating a bitmap from a byte[], Working with Image and Bitmap in c#?, C#: Bitmap Creation using bytes array

My code is aimed to execute a filter on a digital image 8bppIndexed writing the pixel value on a byte [] buffer to be converted again (after some processing to manage gray levels) in a 8BppIndexed Bitmap

My input image is a trivial image created by means of specific perl code: https://www.box.com/shared/zqt46c4pcvmxhc92i7ct

Of course, after executing the filter the output image has lost the first and last rows and the first and last columns, due to the way the filter manage borders, so from the original 256 x 256 image i get a 254 x 254 image.

Just to stay focused on the issue I have commented the code responsible for executing the filter so that the operation really performed is an obvious:

ComputedPixel = InputImage.GetPixel(myColumn, myRow).R;  

I know, i should use lock and unlock but I prefer one headache one by one. Anyway this code should be a sort of identity transform, and at last i use:

 private unsafe void FillOutputImage()
    {           
        OutputImage = new Bitmap (OutputImageCols, OutputImageRows , PixelFormat .Format8bppIndexed);
    ColorPalette ncp = OutputImage.Palette;
    for (int i = 0; i < 256; i++)
        ncp.Entries[i] = Color .FromArgb(255, i, i, i);
    OutputImage.Palette = ncp;

    Rectangle area  = new Rectangle(0, 0, OutputImageCols,  OutputImageRows);
    var data        = OutputImage.LockBits(area, ImageLockMode.WriteOnly, OutputImage.PixelFormat);
    Marshal .Copy    (byteBuffer, 0, data.Scan0, byteBuffer.Length);

    OutputImage.UnlockBits(data);         
}

The output image I get is the following: https://www.box.com/shared/p6tubyi6dsf7cyregg9e

It is quite clear that I am losing a pixel per row, but i cannot understand why:

  1. I have carefully controlled all the parameters: OutputImageCols, OutputImageRows and the byte [] byteBuffer length and content even writing known values as way to test.
  2. The code is nearly identical to other code posted in stackOverflow and elsewhere.

Someone maybe could help to identify where the problem is?

Thanks a lot

© Stack Overflow or respective owner

Related posts about c#