I am trying to display a bitmap that is stored in a binary file.
The binary file is set up like so:
- A Header structure that is 1024 bytes.
- Pixels for the bitmap image (width * height * bytesperpixel - the header struct contains this info).
First I create a byte array:
var headerArray = new byte[Marshal.SizeOf(typeof(TestClass.BMPStruct))]; //size of the struct here is 1024
Then I create a FileStream
on the file and read in the header first. I get bitmap's width + height + bytesperpixel from the header struct, and then read in the right amount of bytes after the header.
I then create a memory stream on those bytes and try creating a new bitmap.
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)
{
}
}
}
On the line bmp = new Bitmap(ms)
, I get a System.ArgumentException in System.Drawing.dll
. My try/catch shows a Parameter is not valid.
exception.
I've seen a few other questions on this site with the same error, but none of the solutions have worked from the ones I've seen.