python怎么在上传图片后压缩图片大小
问题描述
我用的是flask框架,图片处理用的是pillow。
一般上传都是在循环files,然后逐个file.save()我希望在save完成后,执行pillow的压缩逻辑。
但是似乎save是一个I/O操作,存在延迟性,如果直接在file.save()下面直接调用pillow的Image.open,会出错,因为图片数据还没有写入图片。
咋办?
问题解答
回答1:def save(self, dst, buffer_size=16384):'''Save the file to a destination path or file object. If thedestination is a file object you have to close it yourself after thecall. The buffer size is the number of bytes held in memory duringthe copy process. It defaults to 16KB.For secure file saving also have a look at :func:`secure_filename`.:param dst: a filename or open file object the uploaded file is saved to.:param buffer_size: the size of the buffer. This works the same as the `length` parameter of :func:`shutil.copyfileobj`.'''from shutil import copyfileobjclose_dst = Falseif isinstance(dst, string_types): dst = open(dst, ’wb’) close_dst = Truetry: copyfileobj(self.stream, dst, buffer_size)finally: if close_dst:dst.close()
你看save操作不是异步的吖
更新
copyfileobj是个阻塞操作
https://github.com/pallets/we...
回答2:其实这类图片处理,直接使用阿里云的OSS或者七牛等类似的存储功能更好,直接将图片上传到OOS中,然后调用特别的后缀进行指定的图片处理,未来也访问OSS上处理后的地址。这样既可以规避用自己服务器处理图片的负荷,而且也降低了访问的压力,对于降低程序的复杂度也是大有好处的。
回答3:楼主看看Image.open 的fp参数,也可以A filename (string), pathlib.Path object or a file object PIL.Image.open(fp, mode=’r’)
你直接传file给Image.open(file)就可以了吧!
PIL.Image.open(fp, mode=’r’)Opens and identifies the given image file.This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method). See new().Parameters: fp – A filename (string), pathlib.Path object or a file object. The file object must implement read(), seek(), and tell() methods, and be opened in binary mode.mode – The mode. If given, this argument must be “r”.Returns: An Image object.Raises: IOError – If the file cannot be found, or the image cannot be opened and identified.
相关文章:
1. python - 求一个在def中可以实现调用本def满足特定条件continue效果的方法(标题说不太清楚,请见题内描述)2. $fields = $values = [];这条代码一直定义不了,一直报错,老师的源码也是被报错的,执行不了,请问该怎么解决这个问题3. 求一个mySQL安装包4. javascript - mysql插入数据时怎样避免与库中的数据重复?5. mysql数据库做关联一般用id还是用户名6. MySQL中的enum类型有什么优点?7. MySQL 这句 创建表结构语句的错误在哪?8. node.js - 我想让最后进入数据库的数据,在前台最先展示,如何做到?9. 数据库设计 - MySQL数据库主键问题10. MySQL能否给某个字段的值设置有效期?
![$fields = $values = [];这条代码一直定义不了,一直报错,老师的源码也是被报错的,执行不了,请问该怎么解决这个问题](http://www.haobala.com/attached/image/news/202205/093622cb60.png)