Search code examples
pythonpixel

how to change all pixels in a given rectangle


I need to create a function that takes in the dimensions of the rectangle and then the desired pixel color. So far, my function looks like this:

def makeRectangle(width, height, desiredPixel):

    # Begin with a rectangle image with all black pixels
    resultImage = EmptyImage(width, height)

    # Creates the total size of the rectangle image
    size = width * height

    # Change the color of all pixels
    for i in range(width):
        resultImage.setPILPixel(i, width, desiredPixel)

    return resultImage

I think that I need to be using a nested for loop but I can't find a way to get all pixel colors to change. The function I have now produces the middle line of pixels to be changed.


Solution

  • PIL has a function to draw rectangles:

    draw = ImageDraw.Draw(resultImage)
    draw.rectangle([0,0,width,height], fill=desiredPixel)
    

    Looping in Python is slow so it is best to find an optimized function to do this sort of thing.