How to avoid bitmap out of memory when working on very large image for ie: 10.000.000 pixel and above

后端 未结 1 1494
Happy的楠姐
Happy的楠姐 2021-02-12 18:16

Currently i\'m working on a system that load a very large image, with minimum width x heigh >= 10.000.000 pixel.

But the ratio of the user\'s upload image usually do not

1条回答
  •  渐次进展
    2021-02-12 18:32

    You could convert the bitmap to a byte array. Try something like this (looks hackie but i don't know another way):

    int pixelSize = 3;
    int bytesCount = imgHeight * imgWidth * pixelSize;
    byte[] byteArray= new byte[bytesCount];
    
    BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, imgWidth, imgHeight), ImageLockMode.ReadOnly, bitmap.PixelFormat);
    Marshal.Copy(bitmapData.Scan0, byteArray, 0, bytesCount);
    

    Each pixel in this array is represented by 3 bytes (this depends on the bitmap type). So you know that lenght of a bitmap line is 3 * imgWidth. Using this you could simply navigate in the byte array and copy just what you need into a new array.

    You would then create a new bitmap with the desired final size, get the bitmap data and Marshal.Copy the new array into that:

    Bitmap newBitmap = new Bitmap(Width, Height);
    BitmapData newBitmapData = b.LockBits(BoundsRect,
                                    ImageLockMode.WriteOnly,
                                    newBitmap.PixelFormat);
    Marshal.Copy(newByteArray, 0, newBitmapData.Scan0, newBytesCount);
    

    Unlock the bitmaps at the end:

    newBitmap.UnlockBits(newBitmapData );
    bitmap.UnlockBits(bitmapData);
    

    Hope this helps. Cheers.

    0 讨论(0)
提交回复
热议问题