0

I have found the following question: How do we embed images in sphinx docs?

However this image tag assumes the file is in jpg or png:

.. image:: picture.jpg
   :width: 200px
   :height: 100px
   :scale: 50 %
   :alt: alternate text
   :align: right

The issue with that is that jpg and png are not modern formats (also creates a bad speed index in Lighthouse/Google PageSpeed Insights: enter image description here). I would like to use a html tag with a srcset containing of two identical files in two formats. Something like that:

<picture>
   <source srcset="diagram.avif" type="image/avif">
   <img src="diagram.jpg" width="620" height="540">
</picture>

This will serve the way smaller image to all modern browsers, but will serve the png to browsers which don't support avif (e.g. IE). How can you do that in sphinx docs / RST?

Felixkruemel
  • 434
  • 1
  • 4
  • 17

2 Answers2

1

Use the raw directive and your code.

.. raw:: html

    <picture>
      <source srcset="diagram.avif" type="image/avif">
      <img src="diagram.jpg" width="620" height="540">
    </picture>

To copy arbitrary static files, put them in a directory relative to the documentation source files, say _static, place the files there, and then configure the value html_static_path in your conf.py. For example:

html_static_path = [
    '_static',
]
Steve Piercy
  • 13,693
  • 1
  • 44
  • 57
0

You can also use sphinxext-photofinish, the docs are somewhat lacking, but in general, you can leave your image tags as:

.. image:: picture.jpg
   :alt: Alt Text

And it should automatically generate a <picture> tag, try to convert to .webp and fill in the width/height. It is used in frc-docs if you want to see an example.

Itay Ziv
  • 76
  • 1
  • 2
  • 6
  • Hey @Itay Ziv, How do you specify the alternative images formats with it? If it automatically converts it to webp, can it also do that to avif? If not I think I would open an issue on GitHub, might be useful. – Felixkruemel Mar 21 '22 at 17:49
  • Also I really don't know how to use it. Added it to the extensions, still doesn't do anything to image or figure tags... – Felixkruemel Mar 22 '22 at 14:13