Upload Image To Imgur After Resizeing In PIL

2019-09-06 07:18发布

问题:

I am writing a script which will get an image from a link. Then the image will be resized using the PIL module and the uploaded to Imgur using pyimgur. I dont want to save the image on disk, instead manipulate the image in memory and then upload it from memory to Imgur. The Script:

from pyimgur import Imgur
import cStringIO
import requests
from PIL import Image

LINK = "http://pngimg.com/upload/cat_PNG106.png"
CLIENT_ID = '29619ae5d125ae6'
im = Imgur(CLIENT_ID)

def _upload_image(img, title):
    uploaded_image = im.upload_image(img, title=title)
    return uploaded_image.link

def _resize_image(width, height, link):
    #Retrieve our source image from a URL
    fp = requests.get(link)
    #Load the URL data into an image
    img = cStringIO.StringIO(fp.content)
    im = Image.open(img)
    #Resize the image
    im2 = im.resize((width, height), Image.NEAREST)
    #saving the image into a cStringIO object to avoid writing to disk
    out_im2 = cStringIO.StringIO()
    im2.save(out_im2, 'png')
    return out_im2.getvalue()

When I run this script I get this error: TypeError: file() argument 1 must be encoded string without NULL bytes, not str Anyone has a solution in mind?

回答1:

It looks like the same problem as this, and the solution is to use StringIO.

A common tip for searching such issues is to search using the generic part of the error message/string.