Saving Image with PIL


I am trying to save an image that I created from scratch with PIL

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

and I get the following error:

Traceback (most recent call last): File “”, line 1, in
line 523, in runfile
execfile(filename, namespace) File “”, line 125, in“img1.png”) File “”, line 512, in getattr
raise AttributeError(name) AttributeError: PIL

I need help interpreting this error and how to save the image properly as “img1.png” (I am fine with the image being saved to the default save spot).


from PIL import Image as pimg
newImg1 ='RGB', (512,512))

and I get the following error:

…“img1.png”) File
“”, line 1439, in save
save_handler(self, fp, filename) File “”, line 572, in
ImageFile._save(im, _idat(fp, chunk), [(“zip”, (0,0)+im.size, 0, rawmode)]) File “”,
line 481, in _save
e = Image._getencoder(im.mode, e, a, im.encoderconfig) File “”, line 399, in _getencoder
return apply(encoder, (mode,) + args + extra) TypeError: an integer is required

Asked By: Kyle Grage



PIL isn’t an attribute of newImg1 but newImg1 is an instance of PIL.Image so it has a save method, thus the following should work."img1.png","PNG")

Note that just calling a file .png doesn’t make it one so you need to specify the file format as a second parameter.




Answered By: Steve Barnes

Try this:

newImg1 = pimg.as_PIL('RGB', (512,512))
Answered By: Bhartendu

As I hate to see questions without a complete answer:

from PIL import Image
newImg1 ='RGB', (512,512))
for i in range (0,511):
    for j in range (0,511):

which yields a test pattern.

To use array style addressing on the image instead of putpixel, convert to a numpy array:

import numpy as np
pixels = np.asarray(newImg1)
pixels.shape, pixels.dtype
-> (512, 512, 3), dtype('uint8')
Answered By: Sean True
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.