0

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:\Users\rich2\Documents\Python\get_image_stream\app3.py", line 13, in <module> image = base64.b64encode(img.read()).decode("ascii") File "C:\Users\Documents\Python\get_image\venv\lib\site-packages\PIL\Image.py", line 546, in __getattr__ raise AttributeError(name) AttributeError: read 

Im clearly missing something but cannot find a workable answer anywhere.

1
  • Welcome to stackoverflow. Which line is line 13? The code block presents image = base64.b64encode(f.read()).decode("ascii"), the trace shows fault found with img.read(). Commented Jul 31, 2021 at 14:41

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

You attempt to read the image twice. Once is enough.

with urllib.request.urlopen(URL) as url: image = base64.b64encode(url.read()).decode("ascii") 

Comments

0

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") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.