首页 > 解决方案 > 使用 Python ftplib 将内存中的 numpy 图像数组上传到 FTP 服务器会导致一个空文件

问题描述

需要帮助将 numpy 数组图像上传到 FTP 服务器。我已经阅读了一些有关将文件保存在临时文件中的主题,但我已经尝试过但无法正常工作;(

import ftplib
from PIL import Image
from io import BytesIO
import numpy as np

data = np.random.random((100,100))
npArray_image = (255.0 / data.max() * (data - data.min())).astype(np.uint8)

img = Image.fromarray(npArray_image.astype('uint8'))
temp = BytesIO()
img.save(temp, format="PNG")

ftp = ftplib.FTP('ftp.server', 'user', 'pass')
ftp.storbinary('STOR /public_html/imgs/test.png', temp)

我收到了消息

226 文件传输成功

但是上传的文件是空的。

标签: pythonnumpyftppython-imaging-libraryftplib

解决方案


# Suppose numpy image in img1

# Read numpy Image from PIL
image = Image.fromarray(np.uint8(img1)).convert('RGB')

# Read image from local storange using PIL
image = Image.open(r"OutputImageOBJD.png")

temp = io.BytesIO() # This is a file object
image.save(temp, format="png") # Save the content to temp
temp1 = temp.getvalue() # To print bytes string
temp.seek(0) # Return the BytesIO's file pointer to the beginning of the file

# Store image to FTP Server
ftp.storbinary("STOR image_name.png", temp)

推荐阅读