Fill Color of PIL Cropping/Thumbnailing

后端 未结 2 1629
一整个雨季
一整个雨季 2021-02-19 21:58

I am taking an image file and thumbnailing and cropping it with the following PIL code:

        image = Image.open(filename)
        image.thumbnail(size, Image.         


        
2条回答
  •  悲&欢浪女
    2021-02-19 22:34

    Its a bit easier to paste your re-sized thumbnail image onto a new image, that is the colour (and alpha value) you want.

    You can create an image, and speicfy its colour in a RGBA tuple like this:

    Image.new('RGBA', size, (255,0,0,255))
    

    Here there is there is no transparency as the alpha band is set to 255. But the background will be red. Using this image to paste onto we can create thumbnails with any colour like this:

    enter image description here

    If we set the alpha band to 0, we can paste onto a transparent image, and get this:

    enter image description here

    Example code:

    import Image
    
    image = Image.open('1_tree_small.jpg')
    size=(50,50)
    image.thumbnail(size, Image.ANTIALIAS)
    # new = Image.new('RGBA', size, (255, 0, 0, 255))  #without alpha, red
    new = Image.new('RGBA', size, (255, 255, 255, 0))  #with alpha
    new.paste(image,((size[0] - image.size[0]) / 2, (size[1] - image.size[1]) / 2))
    new.save('saved4.png')
    

提交回复
热议问题