【问题标题】:C# Bitmap: "Parameter is invalid" on sizes that aren't a power of 2C# 位图:“参数无效”的大小不是 2 的幂
【发布时间】:2015-11-25 12:45:21
【问题描述】:

我在 C# 中使用 byte[] 数组创建图像,然后将它们转换为 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);

这很好用,直到宽度/高度不是 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)
   (.......)

作为参考,这里是我的using 声明:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Diagnostics;

为什么它不适用于大小不是 2 次方的像素数据集?我怎样才能使它适用于这样的尺寸?

【问题讨论】:

标签: c# .net bitmap pixel


【解决方案1】:

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

【讨论】:

  • 那么使用 32 位 RGBA byte[] 会解决这个问题吗?
  • 是的,刚刚将我的代码切换到 32 位 RGBA - 修复了它 :) 感谢您的帮助!
猜你喜欢
  • 2019-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-28
  • 2010-10-28
  • 1970-01-01
  • 2010-11-24
相关资源
最近更新 更多