简体   繁体   中英

How can I load a static font file for use with PIL in Django?

I'm trying to load a static font file using both settings.STATIC_URL and plain string. In my app I have a folder named /static. and my font's path is /static/fonts/kberry.ttf

font = ImageFont.truetype(path_to_static, 12)

What should path_to_static be? I've literally tried everything and all I get is IOError .

“I've literally tried everything”

Literally everything? Every possible combination of characters that will fit into memory? I'm not sure what you think we can do then :)

But just in case, I'm guessing path_to_static needs to be the full local filesystem path to the font file (rather than a web URL where the file can be found, which is what STATIC_URL would contain).

In my settings file, I declare a SITE_ROOT variable, like this:

import os

SITE_ROOT = os.path.realpath(os.path.dirname(__file__))

That sets SITE_ROOT to the full path of the Django project folder.

If your static folder containing the font file is in the root of your project folder, then you should be able to get its path like this:

import os, settings

path_to_static = os.path.join(settings.SITE_ROOT, 'static/fonts/kberry.ttf')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM