Skip to content

Instantly share code, notes, and snippets.

@SixQuant
Last active October 29, 2020 15:31
Show Gist options
  • Save SixQuant/ff908e12b709d4d9ccbdbb7201f51aad to your computer and use it in GitHub Desktop.
Save SixQuant/ff908e12b709d4d9ccbdbb7201f51aad to your computer and use it in GitHub Desktop.
[Matplotlib speedup savefig]Matplotlib speedup savefig and draw text watermark to the image #Matplotlib #watermark
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
def plt_savefig_with_text_watermark(filename_or_obj, xy, text, color='#E8E8E8', fontsize=12,
format='png', fig=None, **pil_kwargs):
"""
Save the current figure(a little bit faster than direct use fig.savefig) and draw text watermark to the image
"""
if fig is None:
fig = plt.gcf()
# 1. Save the current figure to buffer(a little bit faster than direct use fig.savefig)
canvas = FigureCanvasAgg(fig)
buf, size = canvas.print_to_buffer()
img = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1)
# 2. Draw text watermark to the image
font_name = plt.rcParams['font.sans-serif'][0]
font = ImageFont.truetype(font_name, size=fontsize)
draw = ImageDraw.Draw(img)
draw.text(xy, text, fill=color, font=font)
# 3. Saves this image to file or bytes, the format to use is determined from the filename extension.
img.save(filename_or_obj, format=format, **pil_kwargs)
img.close()
import numpy as np
filename = '/Users/C/Downloads/matplotlib.png'
data = np.random.randn(50).cumsum()
fig = plt.figure()
plt.plot(data)
plt.axis('off')
plt_savefig_with_text_watermark(filename, (8, 8), 'watermark', fontsize=64)
import os
os.system('open -a Preview ' + filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment