pp7sec
pp7sec

Reputation: 75

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.

Upvotes: 1

Views: 382

Answers (2)

Hammad Musaddiq
Hammad Musaddiq

Reputation: 31

# 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)

Upvotes: 3

Martin Prikryl
Martin Prikryl

Reputation: 202272

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)

Upvotes: 1

Related Questions