使用PIL保存图像

51

我正在尝试使用PIL保存我从头开始创建的图像

newImg1 = PIL.Image.new('RGB', (512,512))
pixels1 = newImg1.load()

...

for i in range (0,511):
    for j in range (0,511):
       ...
            pixels1[i, 511-j]=(0,0,0)
        ...

newImg1.PIL.save("img1.png")

我遇到了以下错误:

Traceback (most recent call last): File "", line 1, in File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 523, in runfile execfile(filename, namespace) File "C:\Python27\Lib\site-packages\xy\pyimgmake.py", line 125, in newImg1.PIL.save("img1.png") File "C:\Python27\lib\site-packages\PIL\Image.py", line 512, in getattr raise AttributeError(name) AttributeError: PIL

我需要帮助理解这个错误以及如何正确保存图片为“img1.png”(将图片保存到默认保存位置也可以)。


更新:

from PIL import Image as pimg
...
newImg1 = pimg.new('RGB', (512,512))
...
newImg1.save("img1.png")

我收到以下错误信息:

... newImg1.save("img1.png") File "C:\Python27\lib\site-packages\PIL\Image.py", line 1439, in save save_handler(self, fp, filename) File "C:\Python27\lib\site-packages\PIL\PngImagePlugin.py", line 572, in _save ImageFile._save(im, _idat(fp, chunk), [("zip", (0,0)+im.size, 0, rawmode)]) File "C:\Python27\lib\site-packages\PIL\ImageFile.py", line 481, in _save e = Image._getencoder(im.mode, e, a, im.encoderconfig) File "C:\Python27\lib\site-packages\PIL\Image.py", line 399, in _getencoder return apply(encoder, (mode,) + args + extra) TypeError: an integer is required


3
将newImg1.PIL.save("img1.png")中的PIL.移除,然后尝试执行。 - Srinivas Reddy Thatiparthy
因为创造性地使用新的API方法或在没有查阅任何文档的情况下尝试某些操作而被踩。 - user2665694
那是我的最后一次尝试...我已经更新了帖子,并附上了上述建议产生的错误。 - Kyle Grage
3个回答

73

PIL不是newImg1的属性,但newImg1是PIL.Image的一个实例,因此它具有保存方法,因此以下内容应该有效。

newImg1.save("img1.png","PNG")

请注意,仅仅将文件命名为.png并不能使它成为png格式的文件,因此您需要在第二个参数中指定文件格式。

尝试:

type(newImg1)
dir(newImg1)

help(newImg1.save)

扩展回答。请注意,save函数的参数列表因格式而异。 - Steve Barnes
你在 save 调用中仍然保留了 .PIL,这是导致原始错误的原因。 - Mark Ransom
真糟糕,这就是我在全身麻醉的影响下进行编辑的结果。 - Steve Barnes
谢谢你的新回答。时间已经不够了,所以我只是将 PIL 传递给 matplotlib 函数。出于某种原因,这种方式保存没有任何问题... 我想无论什么方法都可以。 - Kyle Grage
2
文档现在已经说明,格式是从文件名中确定的,因此 newImg1.save('img1.png') 现在应该可以工作了。 - Josiah Yoder

6

由于我不喜欢看到没有完整答案的问题:

from PIL import Image
newImg1 = Image.new('RGB', (512,512))
for i in range (0,511):
    for j in range (0,511):
        newImg1.putpixel((i,j),(i+j%256,i,j))
newImg1.save("img1.png")

这会生成一个测试图案。

如果要在图像上使用数组样式的寻址而不是putpixel,请转换为numpy数组:

import numpy as np
pixels = np.asarray(newImg1)
pixels.shape, pixels.dtype
-> (512, 512, 3), dtype('uint8')

3

试试这个:

newImg1 = pimg.as_PIL('RGB', (512,512))
...
newImg1.save('Img1.png')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接