TypeError when resizing an image with PIL in Pytho

2019-06-25 04:56发布

Note: This is a self-answered question.

I'm trying to resize an image with Python code but I'm getting the following strange error:

Traceback (most recent call last):
  File "resize.py", line 5, in <module>
    logo.save("StartMyProjects_resized.png", format="PNG")
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1439, in save
    save_handler(self, fp, filename)
  File "/usr/lib/python2.7/dist-packages/PIL/PngImagePlugin.py", line 572, in _save
    ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)])
  File "/usr/lib/python2.7/dist-packages/PIL/ImageFile.py", line 481, in _save
    e = Image._getencoder(im.mode, e, a, im.encoderconfig)
  File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 399, in _getencoder
    return apply(encoder, (mode,) + args + extra)
TypeError: an integer is required

And the code I'm using is:

import Image

logo = Image.open("my_image.png")
logo = logo.resize((100, 100), Image.ANTIALIAS)
logo.save("my_image_resized.png")

2条回答
Root(大扎)
2楼-- · 2019-06-25 05:31

For me works, and seem to be portable, the following code:

try:
    from PIL import Image
    from PIL import ImageDraw
except ImportError:
    import Image
    import ImageDraw
查看更多
做个烂人
3楼-- · 2019-06-25 05:37

After some research I found this question on StackOverflow which is not the same but seems to be related.

@SaranshMohapatra said that he had both PIL and Pillow installed (the same as me) and he solved the problem uninstalling one of them. But I solved the problem in a different way.

I just changed the Image import.

From: import Image to: from PIL import Image and that fixed the problem!

So the final snipped looks like this:

from PIL import Image

logo = Image.open("my_image.png")
logo = logo.resize((100, 100), Image.ANTIALIAS)
logo.save("my_image_resized.png")
查看更多
登录 后发表回答