有没有我忽略的明显的方法?我只是想做个缩略图。


当前回答

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))

我使用这个库:

pip install python-resize-image

其他回答

这个脚本将使用PIL (Python成像库)将图像(somepic.jpg)调整为300像素的宽度和与新宽度成比例的高度。它通过确定300像素是原始宽度(img.size[0])的百分比,然后将原始高度(img.size[1])乘以该百分比来实现这一点。将“basewidth”更改为任何其他数字以更改图像的默认宽度。

from PIL import Image

basewidth = 300
img = Image.open('somepic.jpg')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.Resampling.LANCZOS)
img.save('somepic.jpg')

我用这种方法调整了图像的大小,效果很好

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)

要使新图像的宽度和高度是原图像的一半,请使用以下代码:

  from PIL import Image
  im = Image.open("image.jpg")
  resized_im = im.resize((round(im.size[0]*0.5), round(im.size[1]*0.5)))
    
  #Save the cropped image
  resized_im.save('resizedimage.jpg')

调整:用定额调整固定宽度:

from PIL import Image
new_width = 300
im = Image.open("img/7.jpeg")
concat = int(new_width/float(im.size[0]))
size = int((float(im.size[1])*float(concat)))
resized_im = im.resize((new_width,size), Image.ANTIALIAS)
#Save the cropped image
resized_im.save('resizedimage.jpg')

下面的脚本创建所有JPEG图像的漂亮缩略图,保留128x128最大分辨率的纵横比。

from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")

如果你不想/不需要用Pillow打开图像,使用这个:

from PIL import Image

new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))