How do I resize an image using PIL and maintain its aspect ratio?

后端 未结 20 2111
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:30

Is there an obvious way to do this that I\'m missing? I\'m just trying to make thumbnails.

20条回答
  •  萌比男神i
    2020-11-22 02:48

    I will also add a version of the resize that keeps the aspect ratio fixed. In this case, it will adjust the height to match the width of the new image, based on the initial aspect ratio, asp_rat, which is float (!). But, to adjust the width to the height, instead, you just need to comment one line and uncomment the other in the else loop. You will see, where.

    You do not need the semicolons (;), I keep them just to remind myself of syntax of languages I use more often.

    from PIL import Image
    
    img_path = "filename.png";
    img = Image.open(img_path);     # puts our image to the buffer of the PIL.Image object
    
    width, height = img.size;
    asp_rat = width/height;
    
    # Enter new width (in pixels)
    new_width = 50;
    
    # Enter new height (in pixels)
    new_height = 54;
    
    new_rat = new_width/new_height;
    
    if (new_rat == asp_rat):
        img = img.resize((new_width, new_height), Image.ANTIALIAS); 
    
    # adjusts the height to match the width
    # NOTE: if you want to adjust the width to the height, instead -> 
    # uncomment the second line (new_width) and comment the first one (new_height)
    else:
        new_height = round(new_width / asp_rat);
        #new_width = round(new_height * asp_rat);
        img = img.resize((new_width, new_height), Image.ANTIALIAS);
    
    # usage: resize((x,y), resample)
    # resample filter -> PIL.Image.BILINEAR, PIL.Image.NEAREST (default), PIL.Image.BICUBIC, etc..
    # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize
    
    # Enter the name under which you would like to save the new image
    img.save("outputname.png");
    

    And, it is done. I tried to document it as much as I can, so it is clear.

    I hope it might be helpful to someone out there!

提交回复
热议问题