Writing byte stream as jpeg format to disk

Dave Angel davea at ieee.org
Thu Aug 26 22:32:59 CEST 2010


Navkirat Singh wrote:
> O
> <snip>
> I am using Python3 and I receive a byte stream with a jpeg attached sent by the web browser over a socket, which looks like this:
>
> b': image/jpeg\r\nAccept: text/*\r\nReferer: http://127.0.0.1:8001/\r\nAccept-Language: en-us\r\nAccept-Encoding: gzip, deflate\r\nContent-Length: 91783\r\nConnection: keep-alive\r\n\r\n\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00\x84\x00\x03\x02\x02\x03\x02\x02\x03\x03\x03\x03\x04\x03\x03\x04\x05\x08\x05\x05\x04\x04\x05\n\x07\x07\x06\x08\x0c\n\x0c\x0c\x0b\n\x0b\x0b\r\x0e\x12\x10\r\x0e\x11\x0e\x0b\x0b\x10\x16\x10\x11\x13\x14\x15\x15\x15\x0c\x0f
>
> From the above, I need to:
>
> a) Split the header content from the image content, which comes after the keep-alive\r\n\r\n part
>
> b) Then write the image content to file for further use as a jpeg.
>
> Nav
>   
An arbitrary string of bytes is not necessarily valid utf-8, so I'm not 
sure why you haven't been getting errors during that "decode."  In any 
case, such a conversion is not reversible.

I would parse that as bytes, perhaps by searching for 'keep-alive'.  
Then split the byte stream into the two parts, and only convert the 
first part to Unicode (Python 3 string).  For safety, you could check to 
make sure the search pattern only appears once, and potentially decode 
it multiple times.  It'll only make sense once.

DaveA




More information about the Python-list mailing list