F # Create a bitmap from an exception-generated memory stream

I get

System.ArgumentException: 'Parameter is not valid.' 

for some reason.

The line in which I get:

let image = Bitmap.FromStream stream

What i have

let ChangeBitmapColors (bitmap : Bitmap) =
Console.WriteLine bitmap.Size

let width = bitmap.Width
let height = bitmap.Height

let rectangle = new Rectangle(0, 0, width, height)

let bitmapData = bitmap.LockBits(rectangle, Imaging.ImageLockMode.ReadOnly, bitmap.PixelFormat)
let length = bitmapData.Stride * height
let bitmapArray : byte[] = Array.zeroCreate length

Marshal.Copy(bitmapData.Scan0, bitmapArray, 0, length)

bitmap.UnlockBits bitmapData

//todo something with bitmapArray

use stream = new MemoryStream(bitmapArray)                                           

let image = Bitmap.FromStream stream

stream.Dispose |> ignore

image

Any ideas what I'm doing wrong here? Thanks in advance.

+3
source share
1 answer

I don’t know why your code is not working (I checked it and got the same result).

Another option (which works for me) uses Marshal.UnsafeAddrOfPinnedArrayElement

let image = new Bitmap(width, height, bitmapData.Stride, bitmap.PixelFormat,Marshal.UnsafeAddrOfPinnedArrayElement(bi‌​tmapArray, 0))

Edit

Thanks to @ildjarn for the explanation:

, - , , . , , Scanlines

+4

Source: https://habr.com/ru/post/1675729/


All Articles