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

如何在Python中不存本地临时文件直接上传处理后图片至FTP

无需本地保存直接上传rembg生成的掩码图片至FTP服务器

核心思路是利用内存字节流替代本地文件存储,直接将PIL生成的Image对象写入内存缓冲区,再传给FTP客户端完成上传,完全跳过本地文件的创建步骤。

修改后的完整代码

import io
from flask import Flask
from rembg import remove
from PIL import Image
import ftplib

app = Flask(__name__)

input_img_path = "C:/Projects/Python/input/1.jpg"
mask_img_name = 'mask.png'

@app.route("/", methods=["GET"])
def process_and_upload():
    # 读取本地输入图片
    input_img = Image.open(input_img_path)
    # 生成掩码图片
    output = remove(input_img)

    # 创建内存字节流,替代本地文件
    img_buffer = io.BytesIO()
    # 将掩码图片写入内存流(格式设为PNG)
    output.save(img_buffer, format='PNG')
    # 将流指针移到开头,确保FTP能从起始位置读取
    img_buffer.seek(0)

    # 连接FTP并上传
    ftp = ftplib.FTP('host', 'username', 'password')
    # 直接传入内存流对象
    ftp.storbinary(f'STOR {mask_img_name}', img_buffer)
    ftp.quit()

    return "掩码图片已成功上传至FTP"

if __name__ == '__main__':
    app.run(debug=True, port=2000)

关键修改点说明

  • 导入io模块,使用BytesIO创建内存缓冲区,模拟文件对象的行为但不占用磁盘空间
  • 替换output.save(mask_img_path)为output.save(img_buffer, format='PNG'),将图片数据写入内存而非本地路径
  • 调用img_buffer.seek(0)重置流指针:写入数据后指针会停在流末尾,必须移到开头才能让FTP客户端读取完整内容
  • FTP上传时直接传入img_buffer对象,无需再打开本地文件

额外优化建议

  • 移除了原代码中未使用的模块(matplotlib、errno、time、random、os),精简代码结构
  • 把逻辑封装到Flask路由函数中,符合Web服务的使用场景
  • 添加ftp.quit()确保FTP连接正常关闭

内容的提问来源于stack exchange,提问作者Manoj Poosalingam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:55:25