OSError: cannot open resource(pillow錯誤處理)

https://www.jianshu.com/p/c64ae3e9b196html

pillow使用備忘之OSError: cannot open resource錯誤處理python

在使用pillow過程當中,Python程序出現了:OSError: cannot open resource提示。
web

 
pillow出錯提示
  File "E:\06_python\python_demo\MyBlog\web\views\account.py", line 89, in test2
    img, code = create_validate_code()
  File "E:\06_python\python_demo\MyBlog\utils\check_code.py", line 92, in create_validate_code
    strs = create_strs()
  File "E:\06_python\python_demo\MyBlog\utils\check_code.py", line 80, in create_strs
    font = ImageFont.truetype(font_type, font_size)
  File "C:\Users\ic\AppData\Local\Programs\Python\Python35\lib\site-packages\PIL\ImageFont.py", line 280, in truetype
    return FreeTypeFont(font, size, index, encoding, layout_engine)
  File "C:\Users\ic\AppData\Local\Programs\Python\Python35\lib\site-packages\PIL\ImageFont.py", line 145, in __init__
    layout_engine=layout_engine)
OSError: cannot open resource
[11/May/2019 15:07:57] "GET /test2.html HTTP/1.1" 500 92941
Performing system checks...

 

經查此類是常見的字體問題。
在Windows環境,字體通常位於C:\WINDOWS\Fonts文件夾下。用戶能夠到此文件夾中查看Python程序中指定的字體是否存在。
字體

 
Windows的字體文件夾

 

實踐出真知:
字體名稱英文大小寫要一致;
字體名稱是英文的,不是中文。
如簡體黑體常規程序中對應的字體名稱爲simhei.ttf,而簡體仿宋常規對應的字體名爲simfang.ttf
Python程序中直接寫相似華文行楷.ttf、微軟簡粗黑.TTF等中文名稱的字體會出錯。spa

查看對應字體英文名稱的方法很簡單,咱們能夠選中相應字體,右擊屬性項便可找到。
code

 
查看字體的英文名稱

今後圖能夠看出,簡體華文新魏字體對應的英文名稱爲: STXINWEI.TTF,這個英文名用於Python程序才正確。
還有另外一種狀況:
Python程序沒有提示出錯,但中文文字沒法正常顯示(中文輸出顯示成空白方框),則須要更換支持中文的字體。

 

以上是我實踐的結論,能夠供臨時解決上述出錯問題。
但出錯背後的機制,我仍未掌握,歡迎高手交流指正。orm

相關文章
相關標籤/搜索