如何在python中创建法国国旗?

时间:2015-11-11 01:36:11

标签: python python-imaging-library

我试图创建法国国旗而不使用大多数python的内置函数但由于某种原因我的循环不起作用......任何人都可以告诉我为什么?

from PIL import Image
def french():
    flag= Image.new('RGB', (300, 200))
    pixels=flag.getdata()
    pixs= list(pixels)
    r=0
    w=100
    b=200
    while True:
        for x in range(r,(r+100)):
            pixs[x]= (255,0,0)
            flag.putdata(pixs)
            r=+300
        for x in range(w,(w+100)):
            pixs[x]= (255,255,255)
            flag.putdata(pixs)
            w=+300
        for x in range(b,(b+100)):
            pixs[x]=(0,0,255)
            flag.putdata(pixs)
            b=+300
        return (r>60000 or w>60000 or b>60000)
    flag.save('frenchflag.png')
french()

1 个答案:

答案 0 :(得分:2)

  1. 而不是

    # on first pass through the loop, exit the function and return False
    return (r>60000 or w>60000 or b>60000)
    

    我认为你的意思是

    # when we are at the end of the pixel buffer, leave the loop
    if r >= 60000:
        break
    
  2. 像素戳是创建图像的一种非常低效的方式;改为使用PIL.ImageDraw

    from PIL import Image, ImageDraw
    
    RED   = (255,   0,   0)
    WHITE = (255, 255, 255)
    BLUE  = (  0,   0, 255)
    
    def french(fname, width=300, height=200):
        flag = Image.new("RGB", (width, height))
        p, q = width//3, 2*width//3    # bar edge coordinates
        draw = ImageDraw.Draw(flag)
        draw.rectangle((0, 0, p, height), RED)
        draw.rectangle((p, 0, q, height), WHITE)
        draw.rectangle((q, 0, width, height), BLUE)
        flag.save(fname)
    
    french("frenchflag.png")
    

    产生

    enter image description here