Создание растрового изображения из байтового массива - PullRequest
0 голосов
/ 31 октября 2018

Я пытаюсь отобразить растровое изображение, которое хранится в двоичном файле.

Бинарный файл настроен так:

  1. Структура заголовка размером 1024 байта.
  2. Пиксели для растрового изображения (ширина * высота * bytesperpixel - структура заголовка содержит эту информацию).

Сначала я создаю байтовый массив:

var headerArray = new byte[Marshal.SizeOf(typeof(TestClass.BMPStruct))]; //size of the struct here is 1024

Затем я создаю FileStream для файла и сначала читаю в заголовке. Я получаю растровое изображение width + height + bytesperpixel из структуры заголовка, а затем считываю правильное количество байтов после заголовка.

Затем я создаю поток памяти для этих байтов и пытаюсь создать новое растровое изображение.

using (FileStream fs = new FileStream(@"C:\mydrive\testFile.onc", FileMode.Open))
{
    fs.Position = 0; //make sure the stream is at the beginning
    fs.Read(headerArray, 0, 1024); //filestream position is 1024 after this
    var headerStruct = StructsHelper.ByteArrayToStructure<TestClass.BMPStruct>(headerArray);
    int bytesperpixel = headerStruct.BitsPerPixel / 8; //headerStruct.BitsPerPixel is 8 here
    int pixelscount = headerStruct.BitmapWidth * headerStruct.BitmapHeight * bytesperpixel; //BitmapWidth = 296, BitmapHeight = 16, bytesperpixel = 1

    var imageArray = new byte[pixelscount]; //pixelscount = 4736 

    try //now read in the bitmap's bytes
    {
        fs.Read(imageArray, 0, pixelscount); //filestream position is 5760 after this line
    }
    catch (Exception ex)
    {
    }

    Bitmap bmp;
    using (var ms = new MemoryStream(imageArray))
    {
        try
        {
            bmp = new Bitmap(ms); //error thrown here Exception thrown: 'System.ArgumentException' in System.Drawing.dll
            //Parameter is not valid
        }
        catch (Exception ex)
        {
        }
    }
}

На линии bmp = new Bitmap(ms) я получаю System.ArgumentException in System.Drawing.dll. Мой try / catch показывает исключение Parameter is not valid..

Я видел несколько других вопросов на этом сайте с той же ошибкой, но ни одно из решений не сработало с теми, которые я видел.

...