shreyashirday
shreyashirday

Reputation: 900

Bytestring to Image in python

I'm using an API that retrieves media, but the API returns the media as a bytestring...I want to save the bytestring as an image. How do I do this?

i've tried this:

data = *bytestring*

f = open('image.jpg','w')
f.write(str(data))
f.close()

and this compiles successfully, but when I check image.jpg...it is empty or "can't be opened because it is an unknown format"

Upvotes: 2

Views: 7383

Answers (1)

Antoine
Antoine

Reputation: 1070

Try:

f = open('image.jpg','wb')
f.write(data)
f.close()

Why? By default, python convert line ending it found to what is used by the underling platform (on windows for example, it convert '\n' to '\n\r'), which will screw-up you file.

It always consider files to be text files unless you tell explicitly its binary by adding the 'b' option in open(). If you uses the 'b' option it will not convert line endings.

And for the syntax aspect, it is way better to write (it will close the file even in case of exception):

with open('image.jpg','wb') as f:
    f.write(data)

Upvotes: 6

Related Questions