如何通过Python将PIL.Image.Image对象转换为可存储的真实图像?
解决PIL.Image对象转可上传图像的问题
问题出在你直接将PIL Image对象传递给FTP上传方法时,程序默认存储的是该对象的字符串表示(也就是你看到的<PIL.Image.Image ...>),而非实际的图像二进制数据。需要先将PIL对象转换为可传输的图像数据,再进行FTP上传,以下是两种可行方案:
方案1:内存字节流上传(无需生成本地文件)
利用io.BytesIO将图像转为内存中的二进制流,直接上传到FTP:
from PIL import Image import io from ftplib import FTP # 你的原有处理逻辑 output = 'C:/Projects/Python/input/2.jpg' outputimg = remove(Image.open(output)) # 将PIL图像转为字节流 img_byte_stream = io.BytesIO() # 根据图像格式选择对应的format参数(如JPEG/PNG),mode=L灰度图用JPEG即可 outputimg.save(img_byte_stream, format='JPEG') img_byte_stream.seek(0) # 将流指针移到起始位置 # FTP上传操作 ftp = FTP('你的FTP服务器地址') ftp.login('用户名', '密码') # STOR后指定FTP上要保存的文件名 ftp.storbinary('STOR processed_image.jpg', img_byte_stream) ftp.quit()
方案2:保存为本地文件后上传
如果允许生成临时文件,可以先将处理后的图像保存到本地,再上传文件:
from PIL import Image from ftplib import FTP import os # 原有处理逻辑 output = 'C:/Projects/Python/input/2.jpg' outputimg = remove(Image.open(output)) # 临时保存处理后的图像 temp_file_path = 'C:/Projects/Python/temp_processed.jpg' outputimg.save(temp_file_path, format='JPEG') # FTP上传文件 ftp = FTP('你的FTP服务器地址') ftp.login('用户名', '密码') with open(temp_file_path, 'rb') as img_file: ftp.storbinary('STOR processed_image.jpg', img_file) ftp.quit() # 可选:删除临时文件 os.remove(temp_file_path)
注意事项
- 保存图像时的
format参数要与图像模式匹配,比如mode=L是灰度模式,JPEG、PNG格式都支持;如果是带透明通道的mode=RGBA,建议用PNG格式。 - FTP上传必须使用
storbinary方法,因为图像是二进制数据,storlines仅适用于文本文件上传。
内容的提问来源于stack exchange,提问作者Manoj Poosalingam
相关产品推荐
相关产品推荐

