0

我有一些代码可以将 a 复制Bitmap到 Direct3DTexture中以呈现视频。当系统负载过重时,我偶尔会AccessViolationException接到Bitmap.LockBits.

这是一个非常简单的例子:

// Get a PixelFormat.Format24bppRgb image
Bitmap bitmap24 = getVideoFrame();

// Copy into a 32bpp ARGB texture
BitmapData bitmapData = null;
try
{
    // Why am I allowed to do this?
    bitmapData = this.bitmap24.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height),
                                        ImageLockMode.ReadOnly, 
                                        PixelFormat.Format32bppArgb);

    // Blit from bitmapData to texture32
    Texture texture32 = convertBitmapToTexture(bitmapData);
}
finally
{
    if (bitmapData != null)
        this.bitmap.UnlockBits(bitmapData);
}

为什么我知道位图格式是可以调用Bitmap.LockBits和传入?我假设它必须自动从每像素 3 个字节扩展到 4 个。PixelFormat.Format32bppArgbPixelFormat.Format24bppRgbLockBits

LockBits扩展会导致这些异常吗?为什么它只是偶尔发生?

4

1 回答 1

0

LockBits 将以您指定的任何格式将位图存储在内存中。

AccessViolationException当您访问您不应该访问的内存时发生。我可以想到两种情况会发生这种情况:

1)您正在使用ImageLockMode.ReadOnly.. 是否有任何实际尝试更改像素值的地方?也许尝试将其更改为ImageLockMode.ReadWrite,看看是否有帮助。

2)您对缓冲区必须有多大感到困惑,并且您的函数中有一个Marshal.Copy试图convertBitmapToTexture复制超出缓冲区末尾的函数。

当您使用 32bppArgb 时,用int's 而不是s来思考可能更容易。byte这样你就不太可能遇到任何混乱。

于 2012-08-21T23:57:03.353 回答