In Python, Python Image Library 1.1.6, how can I expand the canvas without resizing?

前端 未结 4 949
北恋
北恋 2020-12-05 18:42

I am probably looking for the wrong thing in the handbook, but I am looking to take an image object and expand it without resizing (stretching/squishing) the original image.

4条回答
  •  甜味超标
    2020-12-05 18:45

    Based on interjays answer:

    #!/usr/bin/env python
    
    from PIL import Image
    import math
    
    
    def resize_canvas(old_image_path="314.jpg", new_image_path="save.jpg",
                      canvas_width=500, canvas_height=500):
        """
        Resize the canvas of old_image_path.
    
        Store the new image in new_image_path. Center the image on the new canvas.
    
        Parameters
        ----------
        old_image_path : str
        new_image_path : str
        canvas_width : int
        canvas_height : int
        """
        im = Image.open(old_image_path)
        old_width, old_height = im.size
    
        # Center the image
        x1 = int(math.floor((canvas_width - old_width) / 2))
        y1 = int(math.floor((canvas_height - old_height) / 2))
    
        mode = im.mode
        if len(mode) == 1:  # L, 1
            new_background = (255)
        if len(mode) == 3:  # RGB
            new_background = (255, 255, 255)
        if len(mode) == 4:  # RGBA, CMYK
            new_background = (255, 255, 255, 255)
    
        newImage = Image.new(mode, (canvas_width, canvas_height), new_background)
        newImage.paste(im, (x1, y1, x1 + old_width, y1 + old_height))
        newImage.save(new_image_path)
    
    resize_canvas()
    

提交回复
热议问题