用PIL保存图像

2024-10-06 12:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图保存一个我用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


Tags: inpyimagepilpngsavelibpackages
3条回答

PIL不是newImg1的一个属性,但是newImg1是PIL.Image的一个实例,因此它有一个保存方法,因此下面的操作应该可以工作。

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

请注意,仅仅调用file.png并不能使其成为一个参数,因此需要将文件格式指定为第二个参数。

尝试:

type(newImg1)
dir(newImg1)

以及

help(newImg1.save)

试试这个:

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

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

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')

相关问题 更多 >