"cannot identify image file <_io.BytesIO object"

Getting the error “cannot identify image file <_io.BytesIO object” , while adding contextily basemaps, The same code worked well till date.

import geopandas
import geodatasets
import contextily as cx
import matplotlib.pyplot as plt
import io
import base64
df = geopandas.read_file(geodatasets.get_path("nybb"))
df_wm = df.to_crs(epsg=3857)
ax = df_wm.plot(figsize=(10, 10), alpha=0.5, edgecolor="k")
except Exception as e:

Welcome to the forums.

I thought I could guess the cause: the call to savefig expects a file name but you expect it to write into your BytesIO. The effect you’re seeing is that method turning it into a str file name it can’t open. But if we’re talking about savefig then the documentation supports your expectation.

However, it seems to be achieved by delegation to some plugable rendering class, so maybe the particular renderer you get here doesn’t implement the contract correctly?

A trace-back would pin it down more (and you or someone who knows the library better than I can work it out).

Thanks for the response, savefig will except the str or path-like or binary file-like. I don’t find the problem with savefig :slight_smile:

Yes, I read that in the docs.

Or do you mean it happens at the call to cx.add_basemap? Then I’ve no idea :man_shrugging:, but I still think showing us a trace-back would help others here.


Did you ever figure this out, itsme? I’m encountering the same problem with code that used to work fine!

I got the same error when I tried to add the basemap. The codes worked well a few months ago. Any ideas to solve it?