V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
hustlzp
V2EX  ›  Python

分享一个Flask中对上传图片进行裁剪、缩放、保存的gist

  •  
  •   hustlzp ·
    hustlzp · 2013-12-14 20:22:06 +08:00 · 8150 次点击
    这是一个创建于 3789 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近需要对用户上传的avatar进行处理,首先需要居中裁剪成正方形,然后按需缩放,然后保存。

    于是有了下面的代码片段:


    当然,在调用这个函数前,需要用Flask-WTF做验证确保为图片后缀。
    7 条回复    1970-01-01 08:00:00 +08:00
    rqrq
        1
    rqrq  
       2013-12-14 22:59:22 +08:00
    我觉得是不是应该先根据需要裁减的尺寸比例来缩图,然后再居中裁减多余的部分?
    hustlzp
        2
    hustlzp  
    OP
       2013-12-14 23:34:23 +08:00
    @rqrq 这个还没考虑过哈!

    先缩放后裁剪是不是按理来说速度更快些?
    hustlzp
        3
    hustlzp  
    OP
       2013-12-15 10:14:09 +08:00
    @rqrq 或者先缩再裁得到的图片的质量更高?比如边缘?
    dagger
        4
    dagger  
       2013-12-15 14:05:05 +08:00
    用后缀名验证图片格式不靠谱吧,后缀名在前端作限制就可以了,让经办人直接来识别格式感觉更合适些:
    try:
    image = Image.open(file_storage.stream)
    except IOError:
    ...

    裁剪和缩放的活儿还是交给第三方吧
    http://developers.aviary.com/
    http://open.web.meitu.com/
    如果没法让用户通过交互操作来裁剪上传的图片,体验有可能会不好
    hustlzp
        5
    hustlzp  
    OP
       2013-12-15 14:49:33 +08:00
    @dagger 感谢推荐!后缀验证确实不靠谱。

    http://developers.aviary.com/ 是个好东西,之前不知道哈...

    可以用jcrop( http://deepliquid.com/content/Jcrop.html )实现交互。
    tokki
        6
    tokki  
       2013-12-15 15:53:30 +08:00
    PIL 有一个方法叫ImageOps

    就是切割图片的
    hustlzp
        7
    hustlzp  
    OP
       2013-12-15 16:14:18 +08:00
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1485 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:57 · PVG 00:57 · LAX 09:57 · JFK 12:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.