【发布时间】:2012-03-08 07:38:43
【问题描述】:
能否重写以下函数以使用任何优化机制?我很确定这不是继续逐像素复制的方法。
我读过关于 AlphaBlend 或 BitBlt 的文章,但我不习惯原生代码。
public static Bitmap GetAlphaBitmap(Bitmap srcBitmap)
{
Bitmap result = new Bitmap(srcBitmap.Width, srcBitmap.Height, PixelFormat.Format32bppArgb);
Rectangle bmpBounds = new Rectangle(0, 0, srcBitmap.Width, srcBitmap.Height);
BitmapData srcData = srcBitmap.LockBits(bmpBounds, ImageLockMode.ReadOnly, srcBitmap.PixelFormat);
try
{
for (int y = 0; y <= srcData.Height - 1; y++)
{
for (int x = 0; x <= srcData.Width - 1; x++)
{
Color pixelColor = Color.FromArgb(
Marshal.ReadInt32(srcData.Scan0, (srcData.Stride * y) + (4 * x)));
result.SetPixel(x, y, pixelColor);
}
}
}
finally
{
srcBitmap.UnlockBits(srcData);
}
return result;
}
重要提示:源图像的像素格式(Format32bppRgb)错误,因此我需要调整 Alpha 通道。这是唯一适合我的机制。
src图片像素格式错误的原因解释here.
我尝试了以下选项但没有运气:
- 使用来自 src 的 Graphics.DrawImage 创建新图像并绘制 src 图像。没有保留 alpha。
- 使用 Scan0 表单 src 创建新图像。工作正常,但在 GC 处理 src 图像时出现问题(在另一个 post 中解释);
此解决方案是唯一真正有效的解决方案,但我知道这不是最佳解决方案。我需要知道如何使用 WinAPI 或其他最佳机制来做到这一点。
非常感谢!
【问题讨论】:
-
应该优化到什么程度?使用不安全的块和指针算术是一个可行的选择吗?我有轶事证据表明,在比较二维数组和指针时,速度提高了 3 倍。
标签: c# image winapi bitmap drawing