I am seeking to obtain a Pixbuf
value (package gi-gdkpixbuf
) from an Image PixelRGBA8
value (package JuicyPixels
). I currently have the following code, using pixbufNewFromData
. imageData image
is of type Data.Vector.Storable.Vector Word8
. It seems to work, but I am not confident about low level memory management (as a general topic). Am I doing that aspect correctly? Any advice, gratefully received.
imagePixelRGBA8ToPixbuf :: Image PixelRGBA8 -> IO Pixbuf
imagePixelRGBA8ToPixbuf image = do
let w = imageWidth image
h = imageHeight image
rowStride = w * 4 -- 4 bytes per PixelRGBA8
n = h * rowStride
SV.unsafeWith (imageData image) $ \ptr -> do
pixbufPtr <- mallocBytes n
copyBytes pixbufPtr ptr n
pixbufNewFromData
pixbufPtr
ColorspaceRgb
True -- hasAlpha
8 -- bitsPerSample
(fromIntegral w) -- width
(fromIntegral h) -- height
(fromIntegral rowStride) -- rowStride
(Just free) -- destroyFn
The wider context is that I am trying to present a Diagram B
(packages diagrams-core
, diagrams-rasterific
) using a Picture
(package gi-gtk >= 4.0
) and I do not want to go via a file on disk. I am using diagrams-rasterific
over diagrams-cairo
because the latter produces pixels in (little endian) memory in the byte order B G R A (with premultiplied alpha) and a Pixbuf
expects pixels in memory in the byte order R G B A.