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

后端 未结 20 1875
-上瘾入骨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条回答
  • 2020-11-22 02:50

    My ugly example.

    Function get file like: "pic[0-9a-z].[extension]", resize them to 120x120, moves section to center and save to "ico[0-9a-z].[extension]", works with portrait and landscape:

    def imageResize(filepath):
        from PIL import Image
        file_dir=os.path.split(filepath)
        img = Image.open(filepath)
    
        if img.size[0] > img.size[1]:
            aspect = img.size[1]/120
            new_size = (img.size[0]/aspect, 120)
        else:
            aspect = img.size[0]/120
            new_size = (120, img.size[1]/aspect)
        img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
        img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])
    
        if img.size[0] > img.size[1]:
            new_img = img.crop( (
                (((img.size[0])-120)/2),
                0,
                120+(((img.size[0])-120)/2),
                120
            ) )
        else:
            new_img = img.crop( (
                0,
                (((img.size[1])-120)/2),
                120,
                120+(((img.size[1])-120)/2)
            ) )
    
        new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])
    
    0 讨论(0)
  • 2020-11-22 02:51

    I resizeed the image in such a way and it's working very well

    from io import BytesIO
    from django.core.files.uploadedfile import InMemoryUploadedFile
    import os, sys
    from PIL import Image
    
    
    def imageResize(image):
        outputIoStream = BytesIO()
        imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS) 
        imageTemproaryResized.save(outputIoStream , format='PNG', quality='10') 
        outputIoStream.seek(0)
        uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
    
        ## For upload local folder
        fs = FileSystemStorage()
        filename = fs.save(uploadedImage.name, uploadedImage)
    
    0 讨论(0)
  • 2020-11-22 02:53

    Define a maximum size. Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).

    The proper size is oldsize*ratio.

    There is of course also a library method to do this: the method Image.thumbnail.
    Below is an (edited) example from the PIL documentation.

    import os, sys
    import Image
    
    size = 128, 128
    
    for infile in sys.argv[1:]:
        outfile = os.path.splitext(infile)[0] + ".thumbnail"
        if infile != outfile:
            try:
                im = Image.open(infile)
                im.thumbnail(size, Image.ANTIALIAS)
                im.save(outfile, "JPEG")
            except IOError:
                print "cannot create thumbnail for '%s'" % infile
    
    0 讨论(0)
  • 2020-11-22 02:55
    from PIL import Image
    from resizeimage import resizeimage
    
    def resize_file(in_file, out_file, size):
        with open(in_file) as fd:
            image = resizeimage.resize_thumbnail(Image.open(fd), size)
        image.save(out_file)
        image.close()
    
    resize_file('foo.tif', 'foo_small.jpg', (256, 256))
    

    I use this library:

    pip install python-resize-image
    
    0 讨论(0)
  • 2020-11-22 02:56

    I was trying to resize some images for a slideshow video and because of that, I wanted not just one max dimension, but a max width and a max height (the size of the video frame).
    And there was always the possibility of a portrait video...
    The Image.thumbnail method was promising, but I could not make it upscale a smaller image.

    So after I couldn't find an obvious way to do that here (or at some other places), I wrote this function and put it here for the ones to come:

    from PIL import Image
    
    def get_resized_img(img_path, video_size):
        img = Image.open(img_path)
        width, height = video_size  # these are the MAX dimensions
        video_ratio = width / height
        img_ratio = img.size[0] / img.size[1]
        if video_ratio >= 1:  # the video is wide
            if img_ratio <= video_ratio:  # image is not wide enough
                width_new = int(height * img_ratio)
                size_new = width_new, height
            else:  # image is wider than video
                height_new = int(width / img_ratio)
                size_new = width, height_new
        else:  # the video is tall
            if img_ratio >= video_ratio:  # image is not tall enough
                height_new = int(width / img_ratio)
                size_new = width, height_new
            else:  # image is taller than video
                width_new = int(height * img_ratio)
                size_new = width_new, height
        return img.resize(size_new, resample=Image.LANCZOS)
    
    0 讨论(0)
  • 2020-11-22 02:56

    Open your image file

    from PIL import Image
    im = Image.open("image.png")
    

    Use PIL Image.resize(size, resample=0) method, where you substitute (width, height) of your image for the size 2-tuple.

    This will display your image at original size:

    display(im.resize((int(im.size[0]),int(im.size[1])), 0) )
    

    This will display your image at 1/2 the size:

    display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )
    

    This will display your image at 1/3 the size:

    display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )
    

    This will display your image at 1/4 the size:

    display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )
    

    etc etc

    0 讨论(0)
提交回复
热议问题