代码之家  ›  专栏  ›  技术社区  ›  pfinferno

从字节数组创建位图

  •  0
  • pfinferno  · 技术社区  · 6 年前

    我试图显示一个位图,它存储在一个二进制文件中。

    二进制文件的设置如下:

    1. 1024字节的头结构。
    2. 位图图像的像素(宽度*高度*字节像素-头结构包含此信息)。

    首先,我创建一个字节数组:

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

    然后我创建一个 FileStream 在文件上,首先读取头。我从header结构中得到位图的宽度+高度+字节像素,然后在header之后读取正确的字节数。

    然后在这些字节上创建一个内存流,并尝试创建一个新的位图。

    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 . 我的尝试/捕捉显示 Parameter is not valid. 例外。

    我在这个网站上看到了一些其他的问题,也有同样的错误,但是没有一个解决方案能像我看到的那样奏效。

    0 回复  |  直到 6 年前