簡體   English   中英

Marshal.Copy/UnlockBits 掛起

[英]Marshal.Copy/UnlockBits hangs

用戶選擇圖像的一部分進行剪切和粘貼操作。 我創建了一個新的 bitmap,將所選部分粘貼到新圖像中,擦除源數組並將其粘貼回舊圖像中。 工作但至少有一半時間它掛起並嘗試讀取或寫入受保護的 memory。這通常表明其他 memory 已損壞。

有什么想法或幫助嗎?

public BitmapSource CutToNew(double left, double top, double width, double height, double pageWidth, double pageHeight)
{
    var destBmp = new Bitmap((int)pageWidth, (int)pageHeight);
    var g = Graphics.FromImage(destBmp);
    g.FillRectangle(new SolidBrush(Color.White), 0, 0, 
       (int)pageHeight, (int)pageWidth);
    g.Dispose();

    var croppedArea = new Rectangle((int)left, (int)top, (int)width, (int)height);
    BitmapData croppedSource = _bitmapImage.LockBits(croppedArea, 
          ImageLockMode.ReadWrite, BitmapImage.PixelFormat);
    var croppedDestArea = new Rectangle((int)left, (int)top, (int)width, (int)height);
    BitmapData croppedDest = destBmp.LockBits(croppedDestArea, 
          ImageLockMode.WriteOnly, BitmapImage.PixelFormat);

    // Create data array to hold bmpSource pixel data
    int stride = croppedSource.Stride;
    int numBytes = stride * (int)height;
    var srcData = new byte[numBytes];
    var destData = new byte[numBytes];

    Marshal.Copy(croppedSource.Scan0, srcData, 0, numBytes);
    //Tried creating a separate array in case that helped.
    Array.Copy(srcData, destData, srcData.Length);
    //Often hangs here with Attempted to read or write protected memory.
    Marshal.Copy(destData, 0, croppedDest.Scan0, numBytes);

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

    //Blank the source area
    for (int y = 0; y < srcData.Length; y++)
        srcData[y] = 0xFF;

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

    return retVal.bmpSource;
}

private Bitmap _bitmapImage;
public Bitmap BitmapImage
{
    get
    {
        if (_bitmapImage != null)
            return _bitmapImage;

        if (FileImage != null)
        {
            var stream = new MemoryStream(FileImage); //Fileimage=TIFF read from file.
            _bitmapImage = new Bitmap(stream);
            return _bitmapImage;
        }
        return null;
    }
    set
    {
        if (value != null)
        {

            ImageCodecInfo codecInfo = GetImageCodecInfo("TIFF");
             ... implementation to set the bitmap image.

您可能想在創建新的 object 時嘗試指定PixelFormat

例如:

var destBmp = new Bitmap((int)pageWidth, (int)pageHeight, PixelFormat.Format24bppRgb);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM