matplotlib 保存/转换pyplot图到BLOB URL

vwkv1x7d  于 2023-04-06  发布在  其他
关注(0)|答案(1)|浏览(113)

我使用Geopandas从一些PostGIS数据生成一个图,如下所示

db_connection_url = "postgresql://urser:pw@dburl:25060/dbname";
con = create_engine(db_connection_url)  
sql = 'SELECT geom FROM mytable where var > 0.5' 
df = geopandas.GeoDataFrame.from_postgis(sql, con)

我可以很容易地把这个情节保存成这样的jpg

import matplotlib.pyplot as plt
df.plot()
plt.savefig('world.jpg')

问题是我在一个服务器上运行这个程序,我想把结果作为一个blob url而不是一个jpg文件返回,我想在python中这样做,而不需要把fig保存到本地文件系统。

vyu0f0g1

vyu0f0g11#

下面是一个演示代码,展示了如何从图中获取base64代码的图像。

from io import BytesIO, StringIO
import base64
import pandas as pd
import geopandas as gpd
from shapely.geometry import LineString
#import numpy as np
import matplotlib.pyplot as plt

# Create a dataframe from CSV data
df5 = pd.read_csv(StringIO(
"""id longitude latitude
828  4.8906  52.3723
630  4.8892  52.3694
234  4.8863  52.3671"""), sep="\s+")

# Create a LineString from all points in `df5` dataframe
ls = LineString( df5[['longitude','latitude']].to_numpy() )
line_gdf = gpd.GeoDataFrame( [['1021']],crs='epsg:4326', geometry=[ls] )

fig = plt.figure(figsize=[6,7])
ax = fig.gca()

# Plot the data from `line_gdf` geodataframe
line_gdf.plot(color="red", ax=ax);
df5.plot("longitude", "latitude", kind="scatter", ax=ax);

# Get the (plotted) image into memory file
imgdata = BytesIO()
fig.savefig(imgdata, dpi=60, format='png')
imgdata.seek(0)  #rewind the data
imgJpg = imgdata.getvalue()

html = """<html><body><img src="data:image/png;base64,{}"/></body></html>""".format(base64.encodebytes(imgdata.getvalue()).decode())

plt.show()

您将获得嵌入在HTML代码中的base64图像(在html变量中)。在Jupyter notebook中,您可以显示获得的HTML代码如下。

from IPython.display import HTML
HTML(html)

您可能需要的图像的输出数据:

(1) Binary: just get it from the content of `imgJpg` (smaller size)
(2) `base64` data string, which can be obtained from:
base64.encodebytes(imgdata.getvalue()).decode()

警告,一般来说,这将是一个很长的字符串。

相关问题