How to decode a image from a vec<u8> data

Hi,

I have a image in a content struct :
content.header_image type is Option<Vec< u8>>
I can’t change this type.

I would like to decode this image in my template. But I don’t find how to convert it in bytes or string as asked…

#if content.header_image != none [
  #let header_image = content.header_image.as_slice();  // as_slice exists in rust but not in typst...

  #image.decode(header_image, height: 40pt)
]

Can you help me if there is a way to use an image from a vec< u8> type ?

Neither Option nor Vec nor u8 are types that exist in Typst.
I suggest you look at the type shown by:

panic(type(content.header_image))

Perhaps you mean array(int) | none ? In that case bytes will do.

1 Like

Ok, I understand. In typst, it becomes an array. You are right.

#panic(type(content.header_image))

-> "panicked with: array",

So I change my code with that :

#if content.header_image != none [
  #image(bytes(content.header_image), height: 40pt)
]

But, same if I check just before that is different from none, I got this error now :

"cannot loop over none"

The content of content.header_image is :

(\n  73,\n  73,\n  42,\n  0,\n  138,\n  144,\n  0,\n  0,\n  128,\n  63,\n  224,\n  79,\n  240,\n  4,\n  22,\n  13,\n  7,\n  132,\n  66,\n  97,\n  80,\n  184,\n  100,\n  54,\n  29,\n  15,\n  136,\n  68,\n  98,\n  81,\n  56,\n  164,\n  86,\n  45,\n  23,\n  140,\n  70,\n  99,\n  81,\n  184,\n  .. (37184 items omitted),\n)"

Hi @tooremdrama, could you maybe try to revise your post’s title to be a complete question as per the question guidelines:

Good titles are questions you would ask your friend about Typst.

A good title makes the topic easier to grasp. We also hope by adhering to this, we make the information in this forum easy to find in the future. Thanks!


This does not look like an error related to the code you showed. It probably comes from a loop in additional code, not from image data handling.

Compare with this code:

#import "@preview/based:0.2.0": decode64

#let img = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAQAAAAnOwc2AAAAEUlEQVR42mNk+M+AARiHsiAAcCIKAYwFoQ8AAAAASUVORK5CYII="
#let img = decode64(img)

#image(img)

#let invalid = "iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAQAAAAnOwc2AAAAEUlEQVR42mNk+M+AARiHsiAAcCIKAYwFoQ8AAAAASUVO="
#let invalid = decode64(invalid)

#image(invalid)

(the base64 encoded image is generated by this site: https://png-pixel.com/ (10x10, black, opaque))

The first example successfully show the image, which was generated from base64 data decoded to a bytes object. The second example shows a possible error if the image data is invalid: “Failed to decode image (unexpected end of file).”

1 Like

Thank you all for your time.
I use typst by using typst directly in rust. So I finally found the problem from typst and from my code.

Bytes usage works well !!!