gpt4 book ai didi

c# - 位图的 LockBits() 作为 C# 中的不同格式?

转载 作者:行者123 更新时间:2023-11-30 14:48:02 25 4
gpt4 key购买 nike

我最近偶然发现了这个关于在 C# 中将位图格式转换为 24 位 RGB 的问题的答案:Faster copying of images to change their PixelFormat ,其中所选答案说明如下:

Another way is to lock the bits without the alpha channel and then copy the memory to a new bitmap

以下代码作为示例提供(为简洁起见进行了简化):

public static Bitmap RemoveAlphaChannel(Bitmap bitmap) {
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
Bitmap bitmapDest = new Bitmap(bitmap.Width, bitmap.Height, PixelFormat.Format24bppRgb);
BitmapData data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
BitmapData dataDest = bitmapDest.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb);
int bitmapSize = data.Stride * data.Height;
Buffer.MemoryCopy(dataDest.Scan0, data.Scan0, bitmapSize, bitmapSize);
bitmap.UnlockBits(data);
bitmapDest.UnlockBits(dataDest);
return bitmapDest;
}

让我们使用此函数将 32 位 ARGB 图像转换为 24 位 RGB。我有以下问题:

  1. 如何将 32 位位图锁定为 24 位位图,为什么允许这样做?
  2. 现在原始位图中每个像素的 RGB 分量如何连续? Alpha 组件去哪儿了?步幅发生了什么变化?
  3. 将位图的位锁定为不同的格式会导致在幕后创建位图的副本吗?

最佳答案

这只是 GDI+ 提供的便利。重要的是,使用与您要应用的特定算法配合良好的格式访问像素通常更加方便和快捷。

32bppPArgb 格式最适合尽快将位图渲染到屏幕上,它与视频帧缓冲区格式兼容,因此无需转换。典型的渲染速度比任何其他像素格式快 10 倍。但是 PArgb 在代码中操作起来非常笨拙。 R、G 和 B channel 值被 alpha 值校正,您必须再次将其除以恢复原始 RGB 值。要求 Argb 格式一下子解决了这个问题。

同样,24bppRgb 格式很尴尬,您必须使用 byte* 来访问像素 channel 。这需要每个像素 3 次内存访问,大大降低了代码速度。请求 32bppArgb 允许使用 int*,速度更快,并且允许您忽略步幅。

这些转换没有什么特别复杂的。但它们不是是免费的,GDI+ 必须完成分配临时存储和来回转换像素值的工作。我在我的 pokey 笔记本电脑上使用 1000 x 1000 位图和 ImageLockMode.ReadWrite 对其进行了分析:

32bppArgb => 32bppArgb  : 0.002 msec
32bppPArgb => 32bppArgb : 5.6 msec
32bppArgb => 24bppRgb : 5.6 msec
32bppPArgb => 24bppRgb : 5.6 msec

我测量了您的 RemoveAlphaChannel() 方法的性能,使用 memcpy() 在同一个 32bppArgb 1000 x 1000 位图上进行复制。对于所需的单个 ImageLockMode.ReadOnly 像素转换,我得到了 2.8 毫秒,对于副本,我得到了 2.8 毫秒。 GDI+ 提供的 Graphics.DrawImage() 方法的速度大约是它的两倍,耗时 9.3 毫秒。

关于c# - 位图的 LockBits() 作为 C# 中的不同格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42735499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com