import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Noto Sans CJK SC', 'SimHei', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
"""
HTML 转图片中文无乱码示例
"""
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import io
import base64
font_path = '/usr/share/fonts/google-noto-cjk/NotoSansCJK-Regular.ttc'
font_prop = FontProperties(fname=font_path)
font_prop_title = FontProperties(fname=font_path, size=16, weight='bold')
font_prop_label = FontProperties(fname=font_path, size=12)
fig, ax = plt.subplots(figsize=(10, 6))
fig.suptitle('中文标题示例', fontsize=16, fontproperties=font_prop_title)
ax.plot([1, 2, 3, 4], [1, 4, 2, 3], label='数据曲线')
ax.set_xlabel('X 轴', fontsize=12, fontproperties=font_prop_label)
ax.set_ylabel('Y 轴', fontsize=12, fontproperties=font_prop_label)
ax.set_title('图表标题', fontsize=12, fontproperties=font_prop_label)
leg = ax.legend()
for text in leg.get_texts():
text.set_fontproperties(font_prop)
for label in ax.get_xticklabels():
label.set_fontproperties(font_prop)
for label in ax.get_yticklabels():
label.set_fontproperties(font_prop)
ax.annotate('最高点', xy=(2, 4), xytext=(2.5, 4.5),
fontproperties=font_prop,
arrowprops=dict(arrowstyle='->'))
buf = io.BytesIO()
plt.savefig(buf, dpi=100, bbox_inches='tight', format='png')
buf.seek(0)
img_base64 = base64.b64encode(buf.read()).decode('utf-8')
plt.close()
print(f"✅ 生成成功!图片大小:{len(img_base64)} bytes")