def fig2bytes(fig, encode='png', dpi=None):
    """
    Convert matplotlib.figure.Figure object to image bytes.
    """
    import io
    buf = io.BytesIO()
    fig.savefig(buf, format=encode, dpi=None)
    buf.seek(0)
    img_bytes = buf.read()
    buf.close()
    return img_bytes
