python os open_Python中的Oserror:无法打开资源,之,OSErrorcannotopenresource
from PIL import Image, ImageDraw, ImageFont
background_image = Image.open(background_image)
background_image = background_image.convert('RGBA')
最近自然在畫圖啦!先打開一個背景圖,備注一下Image.open()打開的是圖片文件,所以如果是文件路徑要記得轉化哦!教你們一個小技巧,打開網絡圖片(運行時記得換張圖片,怕嚇到你們)
response = req.get("https://cdn.pixabay.com/photo/2020/04/03/07/26/eye-4997724__340.png")
image = Image.open(BytesIO(response.content))
簡單的添加一個圖標:
# 圖標 x y x+w x+h
icon_box = (96, 99, 96 + 90, 99 + 42)
icon_region = poster_icon_url.resize((icon_box[2] - icon_box[0], icon_box[3] - icon_box[1]))
background_image.paste(icon_region, icon_box)
前面一大堆跟我們的標題都沒有關系,接下來重點:
from PIL import Image, ImageDraw, ImageFont
import textwrap
# 添加一個標題
# 設置需要顯示的字體
# 第三方庫存在該字體的寫法如下:
# fontpath = "font/msyh.ttc"
# 項目中存在該字體的寫法如下: zby/config/msyh.ttc這個是我的項目結構然后在config加了字體
# fontpath = r"../config/msyh.ttc"
# 解決Linux上報錯OSError: cannot open resource的寫法:
fontpath = "/usr/share/fonts/MSYH.TTC"
font = ImageFont.truetype(fontpath, 44)
draw = ImageDraw.Draw(background_image)
# 繪制標題 width=20 20個字的大小
item_title = textwrap.wrap(item_title, width=20)
draw.text((210, 90), item_title[0], font=font, fill=(51, 51, 51))
# 換行
draw.text((90, 165), item_title[1], font=font, fill=(51, 51, 51))
中間有一個 :fontpath = "/usr/share/fonts/MSYH.TTC",解釋解釋:
Linux
查看字體
fc-list
安裝
yum -y install fontconfig
安裝成功后會看到/usr/share/fonts 的目錄
cd /usr/share/fonts 進入目錄后添加需要的字體
重啟
fc-cache -fv
畫圖結尾一下
from io import BytesIO
# 單元測試時會彈出你生成的海報
background_image.show()
a = BytesIO()
background_image.save(a, 'png')
a.seek(0)
return a
總結
以上是生活随笔為你收集整理的python os open_Python中的Oserror:无法打开资源,之,OSErrorcannotopenresource的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring boot 邮件端口_不会吧
- 下一篇: 福特f150原厂尾灯17+19款通用吗?