PIL Image.resize()不调整图片大小 [英] PIL Image.resize() not resizing the picture

查看:588
本文介绍了PIL Image.resize()不调整图片大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些奇怪的问题,PIL没有调整图像大小。

I have some strange problem with PIL not resizing the image.

def handle_uploaded_image(i, u):
    # resize image  
    from PIL import Image
    img = Image.open(i)
    if img.mode not in ('L', 'RGB'):
        img = img.convert('RGB')

    width, height = img.size
    if width == height:
        img.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS)
    elif width > height:
        ratio = floor(width / height)
        newwidth = ratio * 150
        newwidthhalf = floor(newwidth / 2)
        img.resize((newwidth, 150), Image.ANTIALIAS)
        box = 1
        img.crop((newwidthhalf, 0, 150, 150))
    elif height > width:
        ratio = floor(height / width)
        newheight = ratio * 150
        newheighthalf = floor(newheight / 2)
        img.resize((150, newheight), image.ANTIALIAS)
        box = 1 
        img.crop((0, newheighthalf, 150, 150))
    path = '/'.join([settings.MEDIA_ROOT, 'users', u.username, 'mugshotv2.jpg'])
    img.save(path, format='JPEG')

此代码运行没有任何错误,并产生我的图像名为mugshotv2.jpg在正确的文件夹,但它不会调整大小。它做了一些事情,因为图片的大小从120 kb降至20 kb,但尺寸保持不变。

This code runs without any errors and produces me image named mugshotv2.jpg in correct folder, but it does not resize it. It does something to it, because the size of the picture drops from 120 kb to 20 kb, but the dimensions remain the same.

也许您也可以建议使用较少代码将图像裁剪成正方形。我有点想像Image.thumbnail这样做,但它做的是它的尺寸缩小到150像素宽度,高度为100像素。

Perhaps you can also suggest way to crop images into squares with less code. I kinda thought that Image.thumbnail does it, but what it did was that it scaled my image to 150 px by its width, leaving height 100px.

Alan。 p>

Alan.

推荐答案

resize()返回图像的调整大小的副本。它不会修改原来的。正确的使用方法是:

resize() returns a resized copy of an image. It doesn't modify the original. The correct way to use it is:

img = img.resize((150, newheight), image.ANTIALIAS)

来源

我想你正在寻找的是ImageOps.fit功能。从PIL 文档

I think what you are looking for is the ImageOps.fit function. From PIL docs:


ImageOps.fit(图像,大小,方法,出血,居中)=>图像

ImageOps.fit(image, size, method, bleed, centering) => image

返回尺寸和裁剪版本的
图像,裁剪到要求的
宽高比和大小。大小
参数是请求的输出大小
(以像素为单位),以(宽,高)
元组的形式给出。

Returns a sized and cropped version of the image, cropped to the requested aspect ratio and size. The size argument is the requested output size in pixels, given as a (width, height) tuple.

这篇关于PIL Image.resize()不调整图片大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆