Generate 16-bit grayscale bitmap data and save to file

I am trying to generate a 16 bit grayscale bitmap in C # from random data. But he crashed on Marshal .Copy.

Here is my code:

   Bitmap b16bpp;
    private void GenerateDummy16bitImage()
    {

        b16bpp = new Bitmap(IMAGE_WIDTH, IMAGE_HEIGHT, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

        var rect = new Rectangle(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
        var bitmapData = b16bpp.LockBits(rect, ImageLockMode.WriteOnly, b16bpp.PixelFormat);
        // Calculate the number of bytes required and allocate them.
        var numberOfBytes = bitmapData.Stride * IMAGE_HEIGHT * 2;
        var bitmapBytes = new short[numberOfBytes];
        // Fill the bitmap bytes with random data.
        var random = new Random();
        for (int x = 0; x < IMAGE_WIDTH; x++)
        {
            for (int y = 0; y < IMAGE_HEIGHT; y++)
            {

                var i = ((y * IMAGE_WIDTH) + x) * 2; // 16bpp

                // Generate the next random pixel color value.
                var value = (short)random.Next(5);

                bitmapBytes[i] = value;         // BLUE
                bitmapBytes[i + 1] = value;     // GREEN
                bitmapBytes[i + 2] = value;     // RED
              //  bitmapBytes[i + 3] = 0xFF;      // ALPHA
            }
        }
        // Copy the randomized bits to the bitmap pointer.
        var ptr = bitmapData.Scan0;
        Marshal.Copy(bitmapBytes, 0, ptr, numberOfBytes);//crashes here

        // Unlock the bitmap, we're all done.
        b16bpp.UnlockBits(bitmapData);

        b16bpp.Save("random.bmp", ImageFormat.Bmp);
        Debug.WriteLine("saved");
    }

      

The exception is:

An unhandled exception of type 'System.AccessViolationException' occurred in mscorlib.dll

This is not my code. I found it in relation to 32 bit bitmaps and modified. But, I think I am missing something as I am fairly new to C #.

Basically, all I need is to wrap arrays of shorts in BitmapData.

+3


source to share


2 answers


I have corrected some of your mistakes (mostly wrong sizes). But it will still break on b16bpp.Save()

because GDI + doesn't support saving 16-bit grayscale images .

Bitmap b16bpp;
private void GenerateDummy16bitImage()
{

    b16bpp = new Bitmap(IMAGE_WIDTH, IMAGE_HEIGHT, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

    var rect = new Rectangle(0, 0, IMAGE_WIDTH, IMAGE_HEIGHT);
    var bitmapData = b16bpp.LockBits(rect, ImageLockMode.WriteOnly, b16bpp.PixelFormat);
    // Calculate the number of bytes required and allocate them.
    var numberOfBytes = bitmapData.Stride * IMAGE_HEIGHT;
    var bitmapBytes = new short[IMAGE_WIDTH * IMAGE_HEIGHT];
    // Fill the bitmap bytes with random data.
    var random = new Random();
    for (int x = 0; x < IMAGE_WIDTH; x++)
    {
        for (int y = 0; y < IMAGE_HEIGHT; y++)
        {

            var i = ((y * IMAGE_WIDTH) + x); // 16bpp

            // Generate the next random pixel color value.
            var value = (short)random.Next(5);

            bitmapBytes[i] = value;         // GRAY
        }
    }
    // Copy the randomized bits to the bitmap pointer.
    var ptr = bitmapData.Scan0;
    Marshal.Copy(bitmapBytes, 0, ptr, bitmapBytes.Length);

    // Unlock the bitmap, we're all done.
    b16bpp.UnlockBits(bitmapData);

    b16bpp.Save("random.bmp", ImageFormat.Bmp);
    Debug.WriteLine("saved");
}

      

Explanation of my changes:



  • bitmapData.Stride

    already IMAGE_WIDTH * BytesPerPixel

    so you don't need to multiply by 2
  • as you declared bitmapBytes

    as short[]

    , it should have image size in pixels, not bytes
  • This means you also don't need to multiply i

    by 2
  • since you have a grayscale image it has no cyan, green and red channels, but one single 16-bit gray channel
  • Marshal.Copy occupies length in "array units" not bytes

In general, you were trying to copy the array 8 times at most to the bitmap.

+6


source


This works for System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:



    private static void SaveBmp(Bitmap bmp, string path)
    {
        Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);

        BitmapData bitmapData = bmp.LockBits(rect, ImageLockMode.ReadOnly, bmp.PixelFormat);

        var pixelFormats = ConvertBmpPixelFormat(bmp.PixelFormat);

        BitmapSource source = BitmapSource.Create(bmp.Width,
                                                  bmp.Height,
                                                  bmp.HorizontalResolution,
                                                  bmp.VerticalResolution,
                                                  pixelFormats,
                                                  null,
                                                  bitmapData.Scan0,
                                                  bitmapData.Stride * bmp.Height,
                                                  bitmapData.Stride);

        bmp.UnlockBits(bitmapData);


        FileStream stream = new FileStream(path, FileMode.Create);

        TiffBitmapEncoder encoder = new TiffBitmapEncoder();

        encoder.Compression = TiffCompressOption.Zip;
        encoder.Frames.Add(BitmapFrame.Create(source));
        encoder.Save(stream);

        stream.Close();
    }

    private static System.Windows.Media.PixelFormat ConvertBmpPixelFormat(System.Drawing.Imaging.PixelFormat pixelformat)
    {
        System.Windows.Media.PixelFormat pixelFormats = System.Windows.Media.PixelFormats.Default;

        switch (pixelformat)
        {
            case System.Drawing.Imaging.PixelFormat.Format32bppArgb:
                pixelFormats = PixelFormats.Bgr32;
                break;

            case System.Drawing.Imaging.PixelFormat.Format8bppIndexed:
                pixelFormats = PixelFormats.Gray8;
                break;

            case System.Drawing.Imaging.PixelFormat.Format16bppGrayScale:
                pixelFormats = PixelFormats.Gray16;
                break;
        }

        return pixelFormats;
    }

      

+8


source







All Articles