Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save image in-memory and upload using PIL?

I'm fairly new to Python. Currently I'm making a prototype that takes an image, creates a thumbnail out of it and and uploads it to the ftp server.

So far I got the get image, convert and resize part ready.

The problem I run into is that using the PIL (pillow) Image library converts the image is a different type than that can be used when uploading using storebinary()

I already tried some approaches like using StringIO or BufferIO to save the image in-memory. But I'm getting errors all the time. Sometimes the image does get uploaded but the file appears to be empty (0 bytes).

Here is the code I'm working with:

import os
import io
import StringIO
import rawpy
import imageio
import Image
import ftplib

# connection part is working
ftp = ftplib.FTP('bananas.com')
ftp.login(user="banana", passwd="bananas")
ftp.cwd("/public_html/upload")

def convert_raw():
    files = os.listdir("/home/pi/Desktop/photos")

    for file in files:
        if file.endswith(".NEF") or file.endswith(".CR2"):
            raw = rawpy.imread(file)
            rgb = raw.postprocess()
            im = Image.fromarray(rgb)
            size = 1000, 1000
            im.thumbnail(size)

            ftp.storbinary('STOR Obama.jpg', img)
            temp.close()
    ftp.quit()

convert_raw()

What I tried:

temp = StringIO.StringIO
im.save(temp, format="png")
img = im.tostring()
temp.seek(0)
imgObj = temp.getvalue()

The error I'm getting lies on the line ftp.storbinary('STOR Obama.jpg', img).

Message:

buf = fp.read(blocksize)
attributeError: 'str' object has no attribute read
like image 773
Arash Avatar asked Nov 25 '15 12:11

Arash


People also ask

How do I import a picture into PIL?

To load the image, we simply import the image module from the pillow and call the Image. open(), passing the image filename. Instead of calling the Pillow module, we will call the PIL module as to make it backward compatible with an older module called Python Imaging Library (PIL).

Does PIL work with JPG?

Pillow reads and writes JPEG 2000 files containing L , LA , RGB or RGBA data. It can also read files containing YCbCr data, which it converts on read into RGB or RGBA depending on whether or not there is an alpha channel.


1 Answers

For Python 3.x use BytesIO instead of StringIO:

temp = BytesIO()
im.save(temp, format="png")
ftp.storbinary('STOR Obama.jpg', temp.getvalue())
like image 135
Roberto Leinardi Avatar answered Nov 15 '22 15:11

Roberto Leinardi