Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading