Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to convert image straight from URL to base64 without saving as a file in Python

I'm looking to convert a web-based image to base64. I know how to do it currently by saving the image as a .jpg file and then using the base64 library to convert the .jpg file to a base64 string.

I'm wondering whether I could skip out the step of saving the image first? Thanks!

like image 253
chris Avatar asked Jul 16 '16 05:07

chris


People also ask

How do I encode to Base64 in Python?

In order to encode the image, we simply use the function base64. b64encode(s) . Python describes the function as follows: Encode the bytes-like object s using Base64 and return the encoded bytes.


2 Answers

Using the requests library:

import base64
import requests


def get_as_base64(url):

    return base64.b64encode(requests.get(url).content)
like image 70
user94559 Avatar answered Oct 01 '22 17:10

user94559


Since requests is not an official package, I prefer to use urllib.

from urllib.request import urlopen 
import base64

base64.b64encode(urlopen("http://xxx/yyy/abc.jpg").read())

    
like image 39
ywat Avatar answered Oct 01 '22 15:10

ywat