简体   繁体   中英

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.

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.

Not clear if you are trying to figure out how to loop, or just want to create a new image with a particular color. If the latter, you can specify the background color when you make a new image, so no need for the loop at all:

im = Image.new("RGB", (width, height), "white")

or you can specify the color using fill or just a hex value:

im = Image.new("RGB", (width,height), "#ddd" )

You will need to iterate through both x and y dimensions to change all pixels:

for x in range(width):
    for y in range(height):
        resultImage.setPILPixel(x, y, desiredPixel)

should do the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM