Search code examples
pythonnumpyftppython-imaging-libraryftplib

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


Need help to upload numpy array image to an FTP server. I have read some topic about keep file in temp but I already try and not work ;(

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)

and I got message

226 File successfully transferred

But the uploaded file is empty.


Solution

  • You have to seek a read pointer of the buffer back to the beginning, before you try to upload the buffer:

    temp.seek(0)
    ftp.storbinary('STOR /public_html/imgs/test.png', temp)