yehuda gilad
yehuda gilad

Reputation: 23

convert an image to binary data

I would like to convert a grayscale image into a string of binary data. I successfuly managed to do so but the outcome defines as none instead of string, which means I can't check the lenght. any sugggestions to fix that, or a different code for this idea? thanks.

This is the code I wrote:

def pass_image(image_url):

    str = base64.b64encode(requests.get(image_url).content)

    print(str)
    print "".join(format(ord(x), "b") for x in decodestring(str))

Upvotes: 0

Views: 5718

Answers (1)

GNT
GNT

Reputation: 36

I think the issue is happening because you are naming your variable str. This is the name used in the python class for strings, so essentially you are overwriting the string class definition with your variable, meaning you can no longer use it and its functions (such as len)

I was able to run this code with the following changes, give it a try. I don't totally understand your goal, but hopefully this helps. Also, make sure you return the object you have created if you would like to use it in a different function

import base64
import requests

my_url = '...' # your url here

def pass_image(image_url):
    output = base64.b64encode(requests.get(image_url).content)
    bin = "".join(format(ord(x), "b") for x in base64.decodestring(output))
    return bin # or you could print it

len(pass_image(my_url)) # for the url I used, I got length of 387244

Hope this helps! Good luck.

Upvotes: 1

Related Questions