Reputation: 15
I need to convert GIF to binary because I need to concatenate then the gif with a text string(which is in binary), because I am doing a Web Server in Python. The rest of the code already performs well and is able to load pictures, texts and htmls. For gifs I have this:
elif format == "gif":
corpo = PIL.Image.open(path)
answer = corpo + ("\n").encode('UTF-8') #I need this line to end with a \n because it's the end of a HTTP answer
This gives me the error "TypeError: unsupported operand type(s) for +: 'GifImageFile' and 'bytes'", and, however, I haven't found any way to do what I am trying. Any help? Thank you.
Upvotes: 1
Views: 1701
Reputation: 207475
Your GIF file on disk is already binary and already what a browser will expect if you send a Content-Type: image/gif
so you just need to read its contents like this:
with open('image.gif', 'rb') as f:
corpo = f.read()
Your variable corpo
will then contain a GIF-encoded image, with a header with the width and height, the palette and the LZW-compressed pixels.
Just by way of clarification, when you use:
im = Image.open('image.gif')
PIL will create a memory buffer according to the width and height in the GIF, then uncompress all the LZW-compressed pixels into that buffer. If you then convert that to bytes, you would be sending the browser the first pixel, then the second, then the third but without any header telling it how big the image is and also you'd be sending it uncompressed. That wouldn't work - as you discovered.
Upvotes: 3
Reputation: 73
You'll need to use the .tobytes()
method to get what you want (brief writeup here). Try this modification of your code snippet:
elif format == 'gif':
corpo = PIL.Image.open(path)
corpo_bytes = corpo.tobytes()
answer = corpo_bytes + ("\n").encode('UTF-8') #I need this line to end with a \n because it's the end of a HTTP answer
This might not be exactly what you're looking for, but it should be enough to get you started in the right direction.
Upvotes: 1