Marshal.Copy / UnlockBits hangs

The user selects a portion of the image for cut and paste operation. I create a new bitmap, insert the selected part into the new image, wipe the original array and paste it back into the old image. Works, but at least half of the time it hangs from Attempting to read or write protected memory. This is often an indication that other memory is damaged.

Any thoughts or help?

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.

      

+3


source to share


1 answer


When creating a new object, you can try to specify your own PixelFormat

.

For example:



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

      

+1


source







All Articles