Is there a way to read an imagefile into a binary string?

I know I can use


but this produces something unreadable that looks a bit like hexdata (I'm a newbie here :-). What I am trying to accomplish is to convert it to a string of ones and zeros. Is this possible?

Thx in advance!

Recommended Answers

All 4 Replies

Search this forum for Vega's decimal to binary converter. Your code is reading the data correctly; now you just have to find the right way to display it.


Thank you for you're reply, but I still can't figure out how to do this.
Vesa's codesnippet is meant for decimal types and not for binarystrings (atleast to my understanding ;).

while n >0:
	Bstr=str(n % 2) + Bstr
	n= n>>1

While this works fine for decimals, it does not read binarystrings that I opened trough;

File=open(FILE, "rb")
for line in File:
[INDENT]Bstr=(line % 2) + Bstr[/INDENT]

Because this doesn't work for bin types.

for example;

>>> b=bin(5)
>>> b
>>> (b % 2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting

And this seems pretty logical as it is not an int, float, or decimaltype. How do you suggest I'd use vesa's sample to output a file opened as binary ("rd") to one's and zero's?

Thx in advance!

I took code I had to dump hexadecimal image data and added a binary option to it ,,,

# hexadecimal and binary dump of image file data
# modified to work with Python30

import binascii

    # pick an image file you have in the working directory
    # or give the full file path ...
    image_file = 'py.ico'
    fin = open(image_file, "rb")
    data = fin.read()
except IOError:
    print("Image file %s not found" % imageFile)
    raise SystemExit

# convert every byte of data to the corresponding 2-digit hexadecimal
hex_str = str(binascii.hexlify(data))
# now create a list of 2-digit hexadecimals
hex_list = []
bin_list = []
for ix in range(2, len(hex_str)-1, 2):
    hex = hex_str[ix]+hex_str[ix+1]
    bin_list.append(bin(int(hex, 16))[2:])

bin_str = "".join(bin_list)

The binary string output is pretty useless, since you can never recover any data back.

If you want to send binary image data as a string, you have to use Python module base64.

Thank a lot Vegaseat!

This is exactly what I needed. I know I can't recover any data back. But I'm gonna use it to feed it through a neural net. Seeing the output I think it's not very effective analysing image data (I'm now using PIL for that). But I think it can be very useful while analysing textinput with a neuralnet!

Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.