[Tutor] Saving data as jpg file

Johan Geldenhuys johan at accesstel.com.au
Sun Jun 12 23:47:49 CEST 2011


Hi,

I tried using the "wb" to create and write the file. In a simple test I did
to open an existing jpg file I know is good, putting the data in my new file
and closing it, it worked.

I don't have access to the camera now, but will try it tomorrow.

Thanks

Johan


-----Original Message-----
From: tutor-bounces+johan=accesstel.com.au at python.org
[mailto:tutor-bounces+johan=accesstel.com.au at python.org] On Behalf Of Steven
D'Aprano
Sent: Sunday, 12 June 2011 10:14 AM
To: Tutor at python.org
Subject: Re: [Tutor] Saving data as jpg file

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
_______________________________________________
Tutor maillist  -  Tutor at python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list