C#位图:“参数无效”的大小不是2的幂

sta*_*abs 5 .net c# pixel bitmap

我正在byte[]C#中使用数组创建图像,然后将它们转换为Bitmap,以便将其保存到磁盘。

以下是我的代码中的一些摘录:

// Create an array of RGB pixels
byte[] pixels = new byte[width * height * 3];

// Do some processing here....

// Import the pixel data into a new bitma
Bitmap image = new Bitmap(width, height, width * 3, PixelFormat.Format24bppRgb, GCHandle.Alloc(pixels, GCHandleType.Pinned).AddrOfPinnedObject());

// Save the image
image.Save("testimage.png", ImageFormat.Png);
Run Code Online (Sandbox Code Playgroud)

这很好,直到宽度/高度不是2的幂(即512x512可以工作,但511x511不能工作),然后出现以下错误:

Unhandled Exception: System.ArgumentException: Parameter is not valid.
   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, Int32 stride, PixelFormat format, IntPtr scan0)
   (.......)
Run Code Online (Sandbox Code Playgroud)

供参考,以下是我的using声明:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Diagnostics;
Run Code Online (Sandbox Code Playgroud)

为什么它不能使用大小不为2的幂的像素数据集?如何使它适合这种尺寸?

Nau*_*afa 2

Micke是对的,主要原因是寄存器的 32 位大小为 4 字节,因此为了优化速度和效率,它应该是 4 的倍数, 来源