You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask上传图片时先调整大小再存入数据库的实现方案求助

解决方案

你可以通过Pillow在内存中直接完成图片压缩,完全适配你现有存储逻辑,不需要修改数据库结构或后续的base64编码、存储流程。

第一步:安装依赖

pip install pillow

第二步:新增图片压缩工具函数

在你现有代码中新增如下函数,直接在内存中处理图片二进制流,不会生成临时文件:

from PIL import Image
from io import BytesIO

def compress_image(raw_data, max_dimension=1200, quality=70):
    # 读取原始二进制数据为图片对象
    img = Image.open(BytesIO(raw_data))
    # 等比例缩放图片,避免尺寸过大
    width, height = img.size
    if max(width, height) > max_dimension:
        scale = max_dimension / max(width, height)
        new_width = int(width * scale)
        new_height = int(height * scale)
        img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
    # 处理PNG透明通道问题,避免转JPG时出错
    if img.mode in ("RGBA", "P"):
        img = img.convert("RGB")
    # 把压缩后的图片转成二进制
    output_buffer = BytesIO()
    img.save(output_buffer, format="JPEG", optimize=True, quality=quality)
    return output_buffer.getvalue()

参数说明:max_dimension是图片最大边的像素上限,quality是压缩质量,取值1-100,数值越小压缩率越高、画质越低,可根据需求自行调整。如果需要保留PNG透明特性,可把format改为PNG,或根据原始图片格式动态调整。

第三步:修改接口逻辑适配压缩

你只需要在读取原始文件数据后,调用上述压缩函数即可,后续流程完全不用改动:

@app.route('/gallery/create', methods=['POST'])
def create_gallery():
   title = request.form['title']
   file = request.files['file']
   # 读取原始文件数据
   raw_data = file.read()
   # 新增:调用压缩函数得到压缩后的二进制数据
   compressed_data = compress_image(raw_data)
   # 后续完全沿用你原有逻辑,仅把raw_data替换为compressed_data即可
   render_file = render_picture(compressed_data)

   newFile = Gallery(name=file.filename, data=compressed_data, rendered_data=render_file, title=title)
   db.session.add(newFile)
   db.session.commit()
   db.session.close()

额外优化建议

如果想要更高的压缩率,可把img.save的format参数改为WebP,同等画质下WebP格式体积比JPG小30%左右,确认前端展示支持WebP格式即可使用。


内容的提问来源于stack exchange,提问作者Ibraheem Alibraheem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 08:27:03