如何保存 <ipython.core.display.image object>

How to save <ipython.core.display.image object>

我有可以通过 IPython.core.display.Image

显示的 png 数据

代码示例:

class GoogleMap(object):
    """Class that stores a PNG image"""
    def __init__(self, lat, long, satellite=True,
                    zoom=10, size=(400,400), sensor=False):
        """Define the map parameters"""
        base="http://maps.googleapis.com/maps/api/staticmap?"
        params=dict(
                sensor= str(sensor).lower(),
                zoom= zoom,
                size= "x".join(map(str, size)),
                center= ",".join(map(str, (lat, long) )),
                style="feature:all|element:labels|visibility:off"
                )

        if satellite:
            params["maptype"]="satellite"

        # Fetch our PNG image data
        self.image = requests.get(base, params=params).content
        
        
import IPython
IPython.core.display.Image(GoogleMap(51.0, 0.0).image)

结果:

如何将此图片保存为 png 文件。

我真的很想把它放到一个循环中,所以 1 个 png 文件连续有大约 3 张图片。

谢谢。

您需要做的就是使用 Python 的标准文件写入行为:

img = GoogleMap(51.0, 0.0)
with open("GoogleMap.png", "wb") as png:
    png.write(img.image)

这是访问您想要的三个 lat/long 对的非常简单的方法:

places = [GoogleMap(51.0, 0.0), GoogleMap(60.2, 5.2), GoogleMap(71.9, 8.9)]
for position, place in enumerate(places):
    with open("place_{}.png".format(position), "wb") as png:
        png.write(place.image)

我会留给你编写一个函数,它接受任意 latitude/longitude 对并保存它们的图像。