【问题标题】:How to resize images? [duplicate]如何调整图像大小? [复制]
【发布时间】:2013-05-12 11:57:48
【问题描述】:

我有带有图像字段的表单和我的上传功能:

def handle_uploaded_file(f, gallery):
    directory = settings.GALLERIES_ROOT+'gal_'+str(gallery.id)+'/'

    # check if directory exist
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
    except Exception, e:
        print 'DEBUG (directory): ', e

    # find next pic number, to improve
    i = 1
    for r,d,f in os.walk(directory):
        for file in f:
            if fl.startswith("pic"):
                i += 1

    extension = os.path.splitext(f.name.replace(" ", "_"))[1]
    filename = "pic%03d%s" % (i, extension)

    # saving
    try:
        with open(directory + pf + filename, 'wb+') as destination:
            for chunk in f.chunks():
                destination.write(chunk)
        return True
    except Exception, e:
        print 'DEBUG (file writing problem): ', e
    return False

现在我想调整上传图片的大小并将它们保存到文件 ico[number].[extension] 图片可以是 png 或 jpg、纵向或横向。如何使用纵横比来做到这一点(最终在缩小后裁剪较长的部分)?

【问题讨论】:

    标签: python django image-uploading


    【解决方案1】:

    这只是一个想法,需要PIL模块,减少2倍(size_index=0.5),例如:

    from tkinter import *
    from PIL.ImageTk import PhotoImage
    import os
    
    def images_size(filepath):
        main= Tk()
        imgobj = PhotoImage(file=filepath)
        size=(imgobj.width(), imgobj.height())
        return size
    
    def imageResize(filepath, size_index):
        from PIL import Image
        NEAREST=0
        file_dir=os.path.split(filepath)
        size=images_size(filepath)    # get image size
        new_size=(int(size[0]*size_index), int(size[1]*size_index))  # set new size here
        sourceimage = Image.open(filepath)
        sourceimage.resize(new_size, resample=NEAREST).save(file_dir[0]+'\\ico'+file_dir[1])
        print(file_dir[0]+'\\ico'+file_dir[1])
    
    
    if __name__ == '__main__':
        imageResize('C:\\pict.png', size_index=0.5)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-01-18
      • 2020-10-02
      • 1970-01-01
      • 2014-03-29
      相关资源
      最近更新 更多