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

Uploading in-memory numpy image array to FTP server using Python ftplib results in an empty file

需要帮助将 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 File successfully transferred

但是上传的文件是空的

在尝试上传缓冲区之前,您必须找到缓冲区的读指针回到开头:

temp.seek(0)
ftp.storbinary('STOR /public_html/imgs/test.png', temp)
# 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)