RandomB
RandomB

Reputation: 3749

F# implementation of DirectBitmap: saved blank

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 =
    class
        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

    end

Upvotes: 1

Views: 72

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243106

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

let w = new WrBitmap(10, 10)
w.SetPixel(5, 5, Color.Red)
w.Save("C:/temp/a.png")

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.

Upvotes: 2

Related Questions