代码之家  ›  专栏  ›  技术社区  ›  Red Riding Hood

从数组创建8位位图

  •  1
  • Red Riding Hood  · 技术社区  · 7 年前

                var height = 2;
                var width = 2;
                var output = new byte[4] { 0, 0, 0, 0 };
                var gcHandle = GCHandle.Alloc(output, GCHandleType.Pinned);
    
                var stride = width * sizeof(byte);
                var pointer = gcHandle.AddrOfPinnedObject();
                using (var bitmap = new Bitmap(width, height, stride, PixelFormat.Format8bppIndexed, pointer))
                {
                }
    

    不管我得到什么 System.ArgumentException: 'Parameter is not valid.' ,没有任何内部例外或进一步的细节。

    我不想用 SetPixel

    System.Drawing.Common 4.5.0 .Net Standard 2.0

    1 回复  |  直到 7 年前
        1
  •  1
  •   TheGeneral    7 年前

    你也许可以这样做,但我不确定这是否有效

    unsafe public static void Main()
    {
       var height = 2;
       var width = 2;
       var output = new byte[4] { 1, 2, 3, 4};
       using (var bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
       {
          var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format8bppIndexed);
          Marshal.Copy(data.Scan0, output, 0, 4);
          bitmap.UnlockBits(data);
          bitmap.Save(@"D:\blah.bmp");
       }
    }
    

    Bitmap.LockBits Method

    将位图锁定到系统内存中。

    Marshal.Copy Method

    将数据从托管阵列复制到非托管内存指针,或 从非托管内存指针到托管数组。


    如前所述,只需在32个基点的工作,让你的生活更轻松

    public static void Main()
    {
       var height = 2;
       var width = 2;
       var c = Color.White.ToArgb();
       var output = new int[4] { c, c, c, c };
       using (var bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed))
       {
          var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
    
          Marshal.Copy(output, 0, data.Scan0, 4);
          bitmap.UnlockBits(data);
          bitmap.Save(@"D:\trdy.bmp");
       }
    }