Lockbits跨越1bpp索引图像字节边界

时间:2012-04-06 14:56:54

标签: c# windows graphics

我正在剪切并粘贴一个1bpp索引图像到新图像。

一切正常,直到起始像素为8的除数。在下面的代码中,stride等于相对于矩形宽度的值,直到我达到字节边界。然后步幅等于整个页面的宽度。

var croppedRect = new Rectangle((int)left, (int)top, (int)width, (int)height);
BitmapData croppedSource = _bitmapImage.LockBits(croppedRect, ImageLockMode.ReadWrite, BitmapImage.PixelFormat);
int stride = croppedSource.Stride;

这是一个问题,因为Marshal不是将我选择的区域粘贴到新图像中,而是复制整个页面宽度的横截面,即所选区域的高度。

int numBytes = stride * (int)height;
var srcData = new byte[numBytes];

Marshal.Copy(croppedSource.Scan0, srcData, 0, numBytes);
Marshal.Copy(srcData, 0, croppedDest.Scan0, numBytes);
destBmp.UnlockBits(croppedDest);

1 个答案:

答案 0 :(得分:4)

这是我感兴趣的人的代码。可能有更优化的解决方案,但这是有效的。我正在创建一个白色的整个页面,并在我翻过它时复制新页面中的选定区域。感谢Bob Powell的SetIndexedPixel例程。

protected int GetIndexedPixel(int x, int y, BitmapData bmd)
{
    var index = y * bmd.Stride + (x >> 3);
    var p = Marshal.ReadByte(bmd.Scan0, index);
    var mask = (byte)(0x80 >> (x & 0x7));
    return p &= mask;
}

protected void SetIndexedPixel(int x, int y, BitmapData bmd, bool pixel)
{
    int index = y * bmd.Stride + (x >> 3);
    byte p = Marshal.ReadByte(bmd.Scan0, index);
    byte mask = (byte)(0x80 >> (x & 0x7));
    if (pixel)
        p &= (byte)(mask ^ 0xff);
    else
        p |= mask;
    Marshal.WriteByte(bmd.Scan0, index, p);
}

public DocAppImage CutToNew(int left, int top, int width, int height, int pageWidth, int pageHeight)
{
    var destBmp = new Bitmap(pageWidth, pageHeight, BitmapImage.PixelFormat);
    var pageRect = new Rectangle(0, 0, pageWidth, pageHeight);

    var pageData = destBmp.LockBits(pageRect, ImageLockMode.WriteOnly, BitmapImage.PixelFormat);
    var croppedRect = new Rectangle(left, top, width, height);
    var croppedSource = BitmapImage.LockBits(croppedRect, ImageLockMode.ReadWrite, BitmapImage.PixelFormat);

    for (var y = 0; y < pageHeight; y++)
        for (var x = 0; x < pageWidth; x++)
        {
            if (y >= top && y <= top + height && x >= left && x <= width + left)
            {
                SetIndexedPixel(x, y, pageData,
                                GetIndexedPixel(x - left, y - top, croppedSource) == 0 ? true : false);
                SetIndexedPixel(x - left, y - top, croppedSource, false); //Blank area in original
            }
            else
                SetIndexedPixel(x, y, pageData, false);  //Fill the remainder of the page with white.
        }

    destBmp.UnlockBits(pageData);

    var retVal = new DocAppImage { BitmapImage = destBmp };
    destBmp.Dispose();

    BitmapImage.UnlockBits(croppedSource);
    SaveBitmapToFileImage(BitmapImage);

    return retVal;
}