def img_encode ( arr , * * kwargs ) : sio = BytesIO ( ) imsave ( sio , arr , * * kwargs ) sio . seek ( 0 ) img_format = kwargs [ 'format' ] if kwargs . get ( 'format' ) else 'png' img_str = base64 . b64encode ( sio . getvalue ( ) ) . decode ( ) return 'data:image/{};base64,{}' . format ( img_format , img_str )
python numpy array image base64 encode for html img
Encode ndarray to base64 string image data Parameters ---------- arr : ndarray ( rows cols depth ) kwargs : passed directly to matplotlib . image . imsave
def img_encode(arr, **kwargs):
    """Encode ndarray to base64 string image data
    
    Parameters
    ----------
    arr: ndarray (rows, cols, depth)
    kwargs: passed directly to matplotlib.image.imsave
    """
    sio = BytesIO()
    imsave(sio, arr, **kwargs)
    sio.seek(0)
    img_format = kwargs['format'] if kwargs.get('format') else 'png'
    img_str = base64.b64encode(sio.getvalue()).decode()

    return 'data:image/{};base64,{}'.format(img_format, img_str)