Issue
When i executing this function i get this error: Fail to create pixmap with Tk_GetPixmap in TkImgPhotoInstanceSetSize
. This error occur in this line: fig, ax = plt.subplots()
(line 12). The strange thing is, that this error only occur sometimes (Maybe only 10% of their executes).
Here is my whole function:
from bs4 import BeautifulSoup
from PIL import ImageDraw, Image, ImageFont
from colour import Color
import base64
from io import BytesIO
import matplotlib.pyplot as plt
def getCurrentBatterySOCImage(batterySOC):
red = Color("red")
colors = list(red.range_to(Color("#23b818"), 101))
color = colors[round(batterySOC)].hex
fig, ax = plt.subplots(facecolor="black")
ax.set_facecolor("black")
fig.tight_layout()
ax.axis("off")
ax.bar([1], batterySOC, color=color)
ax.axis([0.6,1.4,0,100])
ax.set_aspect(.02)
tmpfile = BytesIO()
fig.savefig(tmpfile, format="png", pad_inches=0, bbox_inches="tight")
plt.close(fig)
bar = Image.open(tmpfile)
bar = bar.resize((107, 208))
img = Image.new("RGBA", (136, 248), (255, 0, 0, 0))
img.paste(bar, (14, 26), bar)
battery = Image.open("img/battery.png")
img.paste(battery, (0, 0), battery)
font = ImageFont.truetype('font/RobotoMono.ttf', 40)
message = f"{batterySOC}%"
draw = ImageDraw.Draw(img)
w, h = draw.textsize(message, font=font)
draw.text(((136-w)/2, (248-h)/2), f"{batterySOC}%", fill=(255, 255, 255), font=font, stroke_width=2, stroke_fill="black")
tmpfile1 = BytesIO()
img.save(tmpfile1, format="png")
encoded = base64.b64encode(tmpfile1.getvalue()).decode('utf-8')
with open("index.html") as fp:
soup = BeautifulSoup(fp, "html.parser")
soup.find("img", attrs={'id': 'battery'})['src'] = f"data:image/png;base64,{encoded}"
with open("index.html", "w") as fp:
fp.write(soup.decode())
return
Can someone help me to fix this?
Solution
This seems to be a memory issue from this issue, new in Matplotlib 3.5 (vs 3.3)
The recommended way is to switch to 'Agg' backend if possible
Answered By - PiWi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.