# Pixbuf from Image PixelRGBA8

**URL:** <https://discourse.haskell.org/t/pixbuf-from-image-pixelrgba8/10762>\
**Category:** Learn\
**Created:** [November 19, 2024, 9:47pm UTC](https://discourse.haskell.org/t/pixbuf-from-image-pixelrgba8/10762 "2024-11-19T21:47:38Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [November 19, 2024, 9:47pm UTC](https://discourse.haskell.org/t/pixbuf-from-image-pixelrgba8/10762/1 "2024-11-19T21:47:38Z")

</div>

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.

```haskell
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.
