[Tutor] Saving data as jpg file

Steven D'Aprano steve at pearwood.info
Sun Jun 12 02:13:49 CEST 2011


Johan Geldenhuys wrote:
> Hi,
> 
> I have a Axis IP camera that I can send a HTTP command to and the data
> returned is the jpg image.
> 
> When I get this data, I want to save it as a .jpg file, but I think my
> encoding is not correct, because the image is all distorted.

Are you sure that the data produced by the camera isn't already 
distorted? I would expect that anything you do wrong with the jpg file 
(such as the wrong encoding) will corrupt the file, not just distort it.

But I see that you are opening the output file in text mode, and you are 
on Windows:

img_file = "E:\work\img1.jpg"
f = open(img_file, 'w')


You need to open the file in binary mode, as you are writing binary data:

f = open(img_file, 'wb')

My guess is that this is your problem.


Also, using backslashes in pathnames is tricky. You are lucky that the 
above works correctly, but if you move the file, it might not continue 
to work. Python uses backslashes to escape special characters, e.g. \n 
means newline. Try using this as a file name, and you will see what I mean:

example = 'C:\temp\report.txt'

So you need to be *very* careful of using backslashes in pathnames. The 
best practice is to either:


* escape all the backslashes: img_file = "E:\\work\\img1.jpg"

* or use forward slashes: img_file = "E:/work/img1.jpg"


Windows will happily accept / instead of \ and you will save yourself a 
lot of grief in the future.


> I looked at using PIL, but the device I will install my script on can't be
> used to install other packages like this. I'll have to include the modules
> in my own folder.

If you can install modules in your own folder, you could put PIL in your 
folder and then install it.



-- 
Steven


More information about the Tutor mailing list