jsonimagetypst

Embedding a json image into a typst document


I have an image in JSON format that I would like to directly include in a document written with Typst. Is it possible to do something like below?

#let myimage = "
 \"image\": {
    \"mime\": \"image/png\",
    \"data\": iVBORw0K[...]
  }
}"

#image(myimage)

Solution

  • You can read the JSON file using the json function, decode the base64 string using the based package and decode the image data buffer using image.decode.

    Put together, it would look like this:

    #import "@preview/based:0.1.0": base64
    
    #let file = json("image.json")
    #image.decode(base64.decode(file.image.data))
    

    This will read the file image.json, decode the base64 data in its image.data field and decode that as a PNG image. Typst will use the magic bytes within the file to auto-detect the format, but you can also pass the format explicitly in the named argument format of image.decode.

    The JSON file in this example looks like this:

    {
        "image": {
            "type": "image/png",
            "data": "iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAM..."
        }
    }
    

    You can also parse JSON from a string instead of a file by using the json.decode function.