Reputation: 39836
I have a probably very basic problem with PIL's crop function: The cropped image's colors are totally screwed. Here's 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()
The original image:
As you can see, the output's colors are totally messed up...
Thanks in advance for any help!
-Hoff
Upvotes: 4
Views: 1671
Reputation: 308206
Since the call to save
actually produced output, I have to assume that PIL is able to use either a filename or an open file interchangeably. The problem is in 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')
P.S. I tested this and it works:
Upvotes: 1
Reputation: 3081
instead of
output = open('cropped_football.jpg', 'w')
area.save(output)
output.close()
just do
area.save('cropped_football.jpg')
Upvotes: 3