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

3

31

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!

Entoderm answered 16/7, 2016 at 5:56 Comment(1)
If you share the code you have so far (downloading to a file and then converting), it will be easier for people to help you. As it is, I don't even know what library you want to use to fetch the file in the first place.Laryssa
L
83

Using the requests library:

import base64
import requests


def get_as_base64(url):

    return base64.b64encode(requests.get(url).content)
Laryssa answered 16/7, 2016 at 6:2 Comment(3)
if i dont save image so how could i get url of particular image?Aldus
@Aldus : Couldn't the url be a s3 link maybeFormula
base64 returns a bytes type so you may need to do another conversion to get a string type, for example base64.b64encode(requests.get(url).content).decode('utf-8')Bridgid
L
6

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

    
Lydia answered 14/8, 2020 at 14:55 Comment(0)
B
0

Here is my solution::--

from base64 import b64encode
def url_to_base64(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 \
            (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    }
    return b64encode(requests.get(url, headers=headers, timeout=120).content).decode(
        "utf-8"
    )
Bindle answered 10/3, 2023 at 10:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.