Fill Color of PIL Cropping/Thumbnailing

后端 未结 2 1625
一整个雨季
一整个雨季 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

    I altered the code just a bit to allow for you to specify your own background color, including transparency. The code loads the image specified into a PIL.Image object, generates the thumbnail from the given size, and then pastes the image into another, full sized surface. (Note that the tuple used for color can also be any RGBA value, I have just used white with an alpha/transparency of 0.)


    # assuming 'import from PIL *' is preceding
    thumbnail = Image.open(filename)
    # generating the thumbnail from given size
    thumbnail.thumbnail(size, Image.ANTIALIAS)
    
    offset_x = max((size[0] - thumbnail.size[0]) / 2, 0)
    offset_y = max((size[1] - thumbnail.size[1]) / 2, 0)
    offset_tuple = (offset_x, offset_y) #pack x and y into a tuple
    
    # create the image object to be the final product
    final_thumb = Image.new(mode='RGBA',size=size,color=(255,255,255,0))
    # paste the thumbnail into the full sized image
    final_thumb.paste(thumbnail, offset_tuple)
    # save (the PNG format will retain the alpha band unlike JPEG)
    final_thumb.save(filename,'PNG')
    

提交回复
热议问题