python resize image keep aspect ratio

Solutions on MaxInterview for python resize image keep aspect ratio by the best coders in the world

showing results for - "python resize image keep aspect ratio"
Alizee
30 Nov 2016
1using System.Drawing;
2public static Size ResizeKeepAspect(this Size src, int maxWidth, int maxHeight, bool enlarge = false)
3{
4    maxWidth = enlarge ? maxWidth : Math.Min(maxWidth, src.Width);
5    maxHeight = enlarge ? maxHeight : Math.Min(maxHeight, src.Height);
6
7    decimal rnd = Math.Min(maxWidth / (decimal)src.Width, maxHeight / (decimal)src.Height);
8    return new Size((int)Math.Round(src.Width * rnd), (int)Math.Round(src.Height * rnd));
9}
Salvatore
26 Oct 2016
1img {
2    display: block;
3    max-width: 100%;
4    max-height: 100%;
5    width: auto;
6    height: auto;
7}
Malena
23 Jun 2018
1def resize_with_pad(im, target_width, target_height):
2    '''
3    Resize PIL image keeping ratio and using white background.
4    '''
5    target_ratio = target_height / target_width
6    im_ratio = im.height / im.width
7    if target_ratio > im_ratio:
8        # It must be fixed by width
9        resize_width = target_width
10        resize_height = round(resize_width * im_ratio)
11    else:
12        # Fixed by height
13        resize_height = target_height
14        resize_width = round(resize_height / im_ratio)
15
16    image_resize = im.resize((resize_width, resize_height), Image.ANTIALIAS)
17    background = Image.new('RGBA', (target_width, target_height), (255, 255, 255, 255))
18    offset = (round((target_width - resize_width) / 2), round((target_height - resize_height) / 2))
19    background.paste(image_resize, offset)
20    return background.convert('RGB')
21
similar questions
queries leading to this page
python resize image keep aspect ratio