当前位置:编程学习 > 网站相关 >>

web.py上传图片 and PIL 生成缩略图

1、上传图片

1.1、前台模板:

<form action="" method="post" enctype="multipart/form-data"><input type="file" name="myfile" /> <input type="submit" /></form>

1.2、上传图片:


x = web.input(myfile={})
if 'myfile' in x:
    filepath=x.myfile.filename.replace('\\','/')                                       #客户端为windows时注意
    filename=filepath.split('/')[-1]                                                           #获取文件名
    ext = filename.split('.', 1)[1]                                                              #获取后缀
    if ext == 'jpg':                                                                                       #判断文件后缀名
        homedir = os.getcwd()
        filedir = '%s/static/upload' %homedir #要上传的路径
        now=datetime.now()
        t ="%d%d%d%d%d%d" %(now.year,now.month,now.day,now.hour,now.minute,now.second) #以时间作为文件名
        filename = t+'.'+ext
        fout = open(filedir +'/'+ filename,'w')
        fout.write(x.myfile.file.read())
        fout.close()
        message = u'OK!'
        error = False
    else:
        message = u'请上传jpg格式的文件!'
        error = True

2、生成缩略图 www.zzzyk.com

2.1、首先需要安装Python Imaging Library (PIL)
2.2、代码:


def make_thumb(path, sizes=[(98,80),(150,120)]):
    """
    sizes 参数传递要生成的尺寸,可以生成多种尺寸
    """
    base, ext = os.path.splitext(path)
    try:
        im = Image.open(path)
    except IOError:
print ' in  IOError'
        return
    mode = im.mode
    if mode not in ('L', 'RGB'):
        if mode == 'RGBA':
            # 透明图片需要加白色底
            alpha = im.split()[3]
            bgmask = alpha.point(lambda x: 255-x)
            im = im.convert('RGB')
            # paste(color, box, mask)
            im.paste((255,255,255), None, bgmask)
        else:
            im = im.convert('RGB')

    width, height = im.size
    if width == height:
        region = im
    else:
        if width > height:
            delta = (width - height)/2
            box = (delta, 0, delta+height, height)
        else:
            delta = (height - width)/2
            box = (0, delta, width, delta+width)
        region = im.crop(box)

    for size in sizes:
        filename = base + "_" + "%sx%s" % (str(size[0]), str(size[1])) + ".jpg"
        thumb = region.resize((size[0],size[1]), Image.ANTIALIAS)
        thumb.save(filename, quality=100) # 默认 JPEG 保存质量是 75, 不太清楚。可选值(0~100)


2.3、上传图片完毕后调用本方法就可以。


    fout.write(x.myfile.file.read())
    fout.close()
    util.make_thumb(filedir + filename)


2.4、size为可选参数,是数组列表,数组列表种有几个值则会生成几个缩略图。本例中会生成两张。如果自己需要更改则在方法中传一个数组列表就可以了。

 

摘自 python.cn
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,