embedding image into jupyter notebook and exporting to HTML

后端 未结 3 1402
情话喂你
情话喂你 2020-12-31 15:49

I am running Python 3.7 on Windows using pycharm. I have a jupyter notebook and I would like to embed an image into the notebook. I know all the ways of doing standard embed

相关标签:
3条回答
  • 2020-12-31 16:28

    You can install the Unofficial Jupyter Notebook Extensions.

    It has some interesting extensions (e.g. spell checker, collapsible headings, ...). One of the extensions is Export HTML With Embedded Images which exactly does what you want.

    To install Nbextensions using pip do the following:

    $ pip install jupyter_contrib_nbextensions
    $ pip install jupyter_nbextensions_configurator
    $ jupyter contrib nbextension install --user 
    $ jupyter nbextensions_configurator enable --user
    

    Then you will see in your Jupyter homepage a new tab (Nbextensions), where you can enable and configure different extension.

    After enabling the "Export HTML With Embedded Images", you will see the corresponding option in the "File-Download as" menu.

    0 讨论(0)
  • 2020-12-31 16:36

    My complete solution is based on Milania and

    • encoding-an-image-file-with-base64
    • how-to-base64-encode-an-image-using-python
    • BytesIO.getvalue

    the code

        import base64, io, IPython
        from PIL import Image as PILImage
    
        image = PILImage.open(image_path)
    
        output = io.BytesIO()
        image.save(output, format='PNG')
        encoded_string = base64.b64encode(output.getvalue()).decode()
    
        html = '<img src="data:image/png;base64,{}"/>'.format(encoded_string)
        IPython.display.HTML(html)
    
    0 讨论(0)
  • 2020-12-31 16:44

    When you use a code cell to show an image and then export the notebook to an HTML file, the image is converted to Base64 and the code directly used in the src attribute of the <img> tag. You can apply the same procedure with images included in markdown cells.

    1. First, encode your image as Base64, e.g. by using one of the online enocders.
    2. Create a markdown cell and include an <img> tag which uses your Base64 code, e.g.:

      <img src="data:image/png;base64,CODE_FOLLOWS_HERE" />
      
    3. Evaluate the cell and you should already see your image.

    If you now export your notebook to HTML, the image should be included in the file the same way as images from code cells.

    The only disadvantage with this approach is that your markdown cell gets cluttered with the (probably long) Base64 code. However, this is manageable by e.g. using a markdown cell dedicated solely to the image without other content.

    0 讨论(0)
提交回复
热议问题