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

╄→гoц情女王★ 提交于 2019-12-03 11:01:26

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.

Try using graphicsmagick.net library, then use the Crop method on MagickImage. It should still work well under asp.net, and handles huge image files using disk for scratch.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!