Problem with PILON PIL crop: color of cropped image with thread

I have probably a very simple problem with the PIL crop function: the cropped colors of the image are completely screwed. Here is the code:

>>> from PIL import Image >>> img = Image.open('football.jpg') >>> img <PIL.JpegImagePlugin.JpegImageFile instance at 0x00 >>> img.format 'JPEG' >>> img.mode 'RGB' >>> box = (120,190,400,415) >>> area = img.crop(box) >>> area <PIL.Image._ImageCrop instance at 0x00D56328> >>> area.format >>> area.mode 'RGB' >>> output = open('cropped_football.jpg', 'w') >>> area.save(output) >>> output.close() 

Original Image: enter image description here

and exit .

As you can see, the output colors are completely confused ...

Thanks in advance for your help!

-Hoff

+4
source share
3 answers

output should be a file name, not a handler.

+4
source

instead

 output = open('cropped_football.jpg', 'w') area.save(output) output.close() 

just

 area.save('cropped_football.jpg') 
+3
source

Since the save call actually created the result, I have to assume that PIL can use either the file name or the open file interchangeably. The problem is the file mode, which by default will try to convert based on text conventions - a '\ n' will be replaced by '\ r \ n' on Windows. You need to open the file in binary mode:

 output = open('cropped_football.jpg', 'wb') 

PS I tested this and it works:

enter image description here

+1
source

All Articles