Search code examples
c#.netimage-processingsystem.drawinglockbits

Process Bitmap in C# using underlying buffer accessed with Bitmap.LockBits function


I need to do an analysis with an arbitrary image. I would like to start with the easiest example - just copy a image to picturebox.

Bitmap foreImg = new Bitmap("input.jpg");
//output image
Bitmap resImg = new Bitmap(foreImg.Width, foreImg.Height);
unsafe
{
    BitmapData oneBits = foreImg.LockBits(new Rectangle(0, 0, foreImg.Width, foreImg.Height), ImageLockMode.ReadOnly, foreImg.PixelFormat);
    BitmapData thrBits = resImg.LockBits(new Rectangle(0, 0, resImg.Width, resImg.Height), ImageLockMode.WriteOnly, resImg.PixelFormat);

    System.Threading.Tasks.Parallel.For(0, foreImg.Width * foreImg.Height, j =>
    {
        Pixel* pxOne = (Pixel*)((byte*)oneBits.Scan0 + j * sizeof(Pixel));
        Pixel* pxRes = (Pixel*)((byte*)thrBits.Scan0 + j * sizeof(Pixel));
        pxRes->Green = pxOne->Green;
        pxRes->Red = pxOne->Red;
        pxRes->Blue = pxOne->Blue;

     });

    foreImg.UnlockBits(oneBits);
    resImg.UnlockBits(thrBits);
}

In the result of my program the image is distorted Original: original_image After: after_image. What am I doing wrong?


Solution

  • Thanks! The problem was is that PixelFormat of input images does not match with my struct Pixel. Indeed, I wasn't add alpha byte, and in this case I was suppose to use Format24bppRgb.