Python's PIL crop problem: color of cropped image screwed
-
06-07-2019 - |
Question
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
Solution
output
should be a file name, not a handler.
OTHER TIPS
instead of
output = open('cropped_football.jpg', 'w')
area.save(output)
output.close()
just do
area.save('cropped_football.jpg')
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:
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow