none
Raw image data extracted using LockBits is flipped horizontally RRS feed

  • Question

  • I am trying to extract the raw RBG image data from a .BMP file using LockBits.

    The resulting image data is flipped horizontally.

    The code is as follows:

                Bitmap image = new Bitmap(openFileName);

                if((image.PixelFormat == PixelFormat.Format24bppRgb) || (image.PixelFormat == PixelFormat.Format32bppArgb ))
                {
                    tbxPixelFormat.Text = image.PixelFormat.ToString();
                }
                else
                {
                    tbxPixelFormat.Text = "Unsupported Pixel Format";
                    lblConvertStatus.Text = "File Not Supported";
                    return;
                }

                lblConvertStatus.Text = "Starting Conversion";
                data = image.LockBits(new Rectangle(0, 0, image.Width, image.Height),
                    ImageLockMode.ReadOnly,
                    PixelFormat.Format24bppRgb);
                tbxImageWidth.Text = image.Width.ToString();
                tbxImageHeight.Text = image.Height.ToString();
                imageSize = Math.Abs(data.Stride) * image.Height;
                byte[] bytes = new byte[imageSize];
                Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
                image.UnlockBits(data);

                string extension = Path.GetExtension(openFileName);
                outputFileName = openFileName.Replace(extension, ".bin");

                using (BinaryWriter mywriter = new BinaryWriter(File.Open(outputFileName, FileMode.Create)))
                {
                    mywriter.Write(bytes);
                    lblConvertStatus.Text = "Complete. File " + outputFileName + " created";
                }


    Using c++, I can read the .BMP file directly and write out the image data and the image still in it's original orientation.

    What am I missing in using the LockBits method?

    Monday, August 13, 2018 5:30 PM

Answers

  • There are two kinds of bitmaps, and, according to documentation, when bitmap is bottom-up, the Stride is negative.

    In order to write the rows (scan lines) in a different order when Stride is negative, try replacing mywriter.Write(bytes) with a loop like this:

       int index = image.Height * -data.Stride
       for( index += data.Stride; index >= 0; index += data.Stride)
       {
          mywriter.Write( bytes, index, -data.Stride)
       }

    Your C++ program probably uses a different technique (then show details) or a different image.



    • Edited by Viorel_MVP Monday, August 13, 2018 8:31 PM
    • Marked as answer by OneDogProd Tuesday, August 14, 2018 1:23 PM
    Monday, August 13, 2018 8:16 PM