C# - Read Multi-GB Image to Array

Viewed 60

I am trying to read a large image (30.000 x 20.000 pixels²) into an array in C#. The image is in Gray16, so 16bpp.

Currently, I am trying this:

BitmapSource bitmapSource = null;
bitmapSource = new BitmapImage(new Uri(filepath));
int stride = (bitmapSource.PixelWidth * bitmapSource.Format.BitsPerPixel) / 8;
long array_size = bitmapSource.PixelHeight * stride;
Array pixels_byte = Array.CreateInstance(typeof(ushort), array_size);
bitmapSource.CopyPixels(pixels_byte, stride, 0);

This works totally fine for small images (like 10MP and stuff). But for the large image, I get System.OverflowException: 'Arithmetic operation resulted in an overflow' for the last line (CopyPixels).

I understand what this exception usually means - but I do not know how to fix it here. CopyPixels only takes ints, and besides, 1.2 billion for array_size, so still far away from the Int32.MaxValue of 2 billion.

Is there any way to use the buid-in image tools to read in images of this size? The images come encoded as bmp / png / jpeg, so just reading a stream from the disk is not going to cut it.

1 Answers

Since I could not figure out a way to get the .NET libraries to work, I switched over to https://github.com/dlemstra/Magick.NET

Works great, also for large images, and provides ByteArrays, e.g. like so:

using (MagickImage image = new MagickImage(imagePath)
        {
            image.Format = MagickFormat.Gray;
            byte[] imgarr = image.ToByteArray();
        }
Related