Reputation: 77
I am writing this code for a problem in Automate the Boring Stuff with Python. The code is supposed to create a new image that is all black, then put an off-white rectangle in the center of it, leaving a black border. In testing this section of code, I get an error IndexError: image index out of range
on the last line in the code excerpt below.
I have found many other questions addressing this error message, but none of the solutions seem related. The range of pixels I am asking to color seems to be inside the rectangle of the image. I feel like I'm missing something really simple here.
baseIm = Image.new('RGBA', (298, 370), 'black')
for x in range(5, 365):
for y in range(5, 293):
baseIm.putpixel((x, y), (239, 222, 205))
Upvotes: 0
Views: 11067
Reputation: 551
Yes, you did a small mistake, you swapped the column loop and row loop control values. interchange the limit of both range methods of loop x and y.
baseIm = Image.new('RGBA', (298, 370), 'black')
for x in range(5, 293):
for y in range(5, 365):
baseIm.putpixel((x, y), (239, 222, 205))
Upvotes: 1
Reputation: 1186
Your image is 298 pixels wide (dimension x) and 370 pixels tall (dimension y).
The code goes out of range because it tries to set pixels outside the image -- you make x
go through range(5, 365)
.
Why don't you use baseIm.width
and baseIm.height
in your code? Like this:
baseIm = Image.new('RGBA', (370, 298), 'black')
for x in range(5, baseIm.width-5):
for y in range(5, baseIm.height-5):
baseIm.putpixel((x,y), (239, 222, 205))
Upvotes: 1