Writing byte stream as jpeg format to disk

Robert Kern robert.kern at gmail.com
Thu Aug 26 23:32:17 CEST 2010

On 8/26/10 4:17 PM, Navkirat Singh wrote:

> Here is what I needed to do:
> a) Separate image content from header content of the byte stream received from the web browser.
> b) Save the image content to disk for further use.
> Here is what I did. Following is just a snippet:
> 	while True:
> 		buff = socket.recv(8192)
> 		byteStr +=buff
> 		if not buff: break
> 	#--------------ENCODING/DECODING STARTS FROM HERE (since I want to use split/partition functions to separate header content from the image content)
> 	strMsg = byteStr.decode("ISO-8859-1")
> 	listMsg = strMsg.split('\r\n')
> 	#----------------------------
> 	# do some more processing to search the list for the image content, say supposing index is 11
> 	#---------------------------
> 	imageStr = listMsg[11].encode("ISO-8859-1") #Transform the byte string just the way I found it

If your JPEG happens to contain the bytes \r\n, then this will not work. Please 
follow our advice. Split using b'\r\n\r\n' and use the maxsplit=1 argument to 
make sure that you do not split on spurious b'\r\n\r\n' sequences inside the 
JPEG body. Do not decode the bytes.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list