Generate ByteString in Haskell-Chart

169 Views Asked by At

I use Haskell-Chart according to the example eample-1. Haskell-Chart generates content to file

toFile def "example1_big.png" $ do
...

Is it possible generate content of chart to ByteString instead file? I can not find a solution in the documentation.

2

There are 2 best solutions below

1
On BEST ANSWER

Unfortunately this is not possible is a direct manner. toFile calls upon functions in the cairo library like withPDFSurface, withSVGSurface which themselves call into the cairo C-library and only take file names.

You can always write to a temporary file and read the contents back in like this:

import System.IO.Temp  -- from the temporary package
import qualified Data.ByteString.Char8 as BS

...
bs <- withSystemTempFile "chart-XXXXXXX" $ \path _ -> do
        toFile def path $ do ...
        BS.readFile path
0
On

it's possible but only with Diagrams backend which is slower.

`

import Graphics.Rendering.Chart.State(EC, execEC)
import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Diagrams
import qualified Diagrams.Backend.SVG as DSVG
import qualified Diagrams.Prelude as D
import qualified Diagrams.TwoD as D2

toSVG :: (Default r,ToRenderable r) => EC r () -> IO String
toSVG ec = do
    fontSelector <- _fo_fonts def
    let cb = render (toRenderable (execEC ec))(_fo_size def)
    let (w, h) = (800 :: Double, 600 :: Double)
    let env = createEnv vectorAlignmentFns w h fontSelector
    let (d, a) = runBackend env cb
        opts = DSVG.SVGOptions (D2.dims2D w h) Nothing T.empty [] True
        svg = D.renderDia DSVG.SVG opts d
    return $ show svg

`