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!
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.
Using the requests library:
import base64
import requests
def get_as_base64(url):
return base64.b64encode(requests.get(url).content)
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With