Anki Forums

How to access images in your add-on?

I’m making an add-on, and want to use images in HTML when editing the webview.

How can i access images stored in the add-on folder? I’m not sure how to find the correct path for an img tag

from os.path import join, dirname
addon_path = dirname(__file__)
images = join(addon_path, 'your_folder_name')

then img tag would be something like this

"<img src='{}/your_image_name.png'>".format{images}
1 Like

This didn’t work for me.

can i have your code?
i have been using this and it works.

My code is pretty much exactly what you sent:

addon_path = dirname(__file__)
images = join(addon_path, 'images')
content.stats += """<img src='{}/s1.png'>""".format(images)

In my addon folder there’s a folder called images where the picture is held. Any idea why it doesn’t work?

what i meant was the whole file if that’s possible. wanted to test it on my anki.
anyways, i don’t see anything wrong with this part of your code.

Ah. What’s the best way for me to share it with you?

gofile.io if you want to upload the file
you can also copy the whole file and paste it in a code block here

Here’s the code: https://gofile.io/d/PJ82uX

It uses a database too so you’d have to quickly create the folder structure below first
Screenshot 2020-07-21 at 18.46.17

You could try the following:

  • Add the following lines somewhere (in the global scope) to your __init__.py.

    # give permission to access png files
    mw.addonManager.setWebExports(__name__, r'.+\.png')
    # get this add-on's root directory name
    addon_package = mw.addonManager.addonFromModule(__name__)
    # of course you can also use pathlib
    # addon_package = pathlib.Path(__file__).resolve().parent.name
    base_url = f'/_addons/{addon_package}/images'
    
  • Then, replace format(images) with format(base_url).

3 Likes