Solution for How to base64 encode an image from URL rather than file?
is Given Below:
I need to get an image via a URL, and without saving the image locally base64 encode into a string which in then past as an api call via a URL. Im able to do it no problems if i can save the file locally with:
with open(photo.jpg, "rb") as file:
image = [base64.b64encode(file.read()).decode("ascii")]
After some research I thought I had found a way with the following of doing it without saving:
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())
image = base64.b64encode(f.read()).decode("ascii")
however I get the following error:
Traceback (most recent call last):
File "C:Usersrich2DocumentsPythonget_image_streamapp3.py", line 13, in <module>
image = base64.b64encode(img.read()).decode("ascii")
File "C:UsersDocumentsPythonget_imagevenvlibsite-packagesPILImage.py", line 546, in __getattr__
raise AttributeError(name)
AttributeError: read
Im clearly missing something but cannot find a workable answer anywhere.
url.read
already returns a byte string. So your code should just be
from urllib.request import urlopen
import base64
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urlopen(URL) as url:
f = url.read()
image = base64.b64encode(f).decode("ascii")
For future questions please include import statements.
You attempt to read the image twice. Once is enough.
with urllib.request.urlopen(URL) as url:
image = base64.b64encode(url.read()).decode("ascii")
I am not sure what changes have you made because your error trace shows different code. Maybe you are not importing necessary modules. Here’s the full code that worked for me:
import urllib.request
import io
import base64
URL = 'http://www.w3schools.com/css/trolltunga.jpg'
with urllib.request.urlopen(URL) as url:
f = io.BytesIO(url.read())
image = base64.b64encode(f.read()).decode("ascii")