Writing byte stream as jpeg format to disk

Stefan Schwarzer sschwarzer at sschwarzer.net
Thu Aug 26 14:37:44 EDT 2010


Hi Navkirat,

On 2010-08-26 19:22, Navkirat Singh wrote:
> I am programming a webserver, I receive a jpeg file with
> the POST method.The file (.jpeg) is encoded in bytes, I
> parse the bytes by decoding them to a string. I wanted to
> know how i could write the file (now a string) as a jpeg
> image on disk. When I try to encode the same string to a
> bytes and write them in binary format to disk, the file is
> not recognized as jpeg. I would be grateful if someone
> could help me with this.

I guess you mean you "see" a byte string in your server and
want to write that to disk. Assuming the string you got is
the correct image data in the first place, you can, in
Python 2.x, write the string data to disk like this:

    fobj = open("some_image.jpg", "wb")
    fobj.write(byte_string)
    fobj.close()

Note that you should use "wb" as mode to write as binary.
Otherwise you'll get automatic line ending conversion (at
least on Windows) which will give the result you describe.

If my answer doesn't help, you probably need to describe in
more detail what you're doing, including showing some real
code.

Stefan



More information about the Python-list mailing list