Home F# implementation of DirectBitmap: saved blank
Reply: 1

F# implementation of DirectBitmap: saved blank

Paul-AG Published in 2018-01-12 21:02:32Z

I'm trying to set pixels in image and then to save it as PNG. I get PNG file with correct bpp and size but it's totally black. So, I suppose Save works correctly, but either set pixels are lost or set pixels in Bits array have wrong format. Would somebody explain, what's wrong with this code?

type WrBitmap =
        val Width : int
        val Height : int
        val Bits : array<uint32>
        val BitsHandle : GCHandle
        val Bitmap : Bitmap
        val Length : int64
        val mutable Disposed : bool

        new (sizeAsFile : string) =
            let img : Image = Image.FromFile (sizeAsFile)
            new WrBitmap (img.Width, img.Height)

        new (width : int, height : int) =
            let bits = Array.zeroCreate (width * height)
            let bitsHandle = GCHandle.Alloc (bits, GCHandleType.Pinned)
            let bitmap = new Bitmap (width, height, width * 4, PixelFormat.Format32bppArgb, bitsHandle.AddrOfPinnedObject ())
                Width = width
                Height = height
                Bits = bits
                BitsHandle = bitsHandle
                Bitmap = bitmap
                Length = width * height |> int64
                Disposed = false

        member inline __.SetPixel (x : int, y : int, color : Color) =
            let i = x + (y * __.Width)
            let c = color.ToArgb ()
            __.Bits.[i] <- uint32 c

        member inline __.GetPixel (x : int, y : int) =
            let i = x + (y * __.Width)
            let c = __.Bits.[i]
            Color.FromArgb (int c)

        member __.Save (path : string) =
            __.Bitmap.Save (path)

        interface IDisposable with
            member __.Dispose () =
                if __.Disposed <> true then
                    __.Bitmap.Dispose ()
                    __.BitsHandle.Free ()
                    __.Disposed <- true

Tomas Petricek
Tomas Petricek Reply to 2018-01-12 23:54:35Z

I tested your code using the following snippet and it works fine:

let w = new WrBitmap(10, 10)
w.SetPixel(5, 5, Color.Red)

It creates 10x10 bitmap which is all transparent with one red pixel in the middle. So, I suspect that the problem you are seeing is caused by something else.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.301698 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO