Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch image from internet, modify and insert to database in python

I'm trying to save images from one webpage to the database of another.

Here is a cut down version of the code:

POSTER_SIZE = (200, 310)

LargePoster = urllib2.urlopen(PosterURL).read()
SmallPoster = LargePoster.resize(POSTER_SIZE, Image.ANTIALIAS)

conn = MySQLdb.connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, charset='utf8')
cur = conn()
cur.execute("UPDATE `table` SET `poster`=%s WHERE `id`=%d", (SmallPoster, ID))
cur.close()

Note: I do NOT want to keep the aspect ratio, so do not suggest Image.thumbnail() unless it can stretch it.

As you can see, I retrieve the image using urlopen() and read() but it returns a string. I need this string to be of class Image so I can manipulate it using PIL/Pillow and then later have it output as a string so I can send it to the database.

I know for a fact that all the images are compressed using JPEG.

Updated code for Peter

LargePosterString = urllib2.urlopen(MovieMeta['poster']).read()
LargePosterImage = Image.open(StringIO(LargePosterString))

SmallPosterImage = LargePosterImage.resize(POSTER_SIZE, Image.ANTIALIAS)
SmallPosterString = StringIO()

Format = 'JPEG'
SmallPosterImage.save(SmallPosterString.getvalue(), Format)
like image 938
Steen Schütt Avatar asked Jan 21 '26 05:01

Steen Schütt


1 Answers

The docs suggest various ways, of which the simplest is probably to make your string into a thing that looks like a file:

from PIL import Image
from StringIO import StringIO

LargeData = urllib2.urlopen(PosterURL).read()

# read data from string
LargePoster = Image.open(StringIO(LargeData))

# After editing the image, turn it back into a string
# for saving in the database:
result = StringIO()
format = 'JPEG' # or whatever you want
SmallPoster.save(result, format)
SmallPosterString = result.getvalue()
like image 185
Peter Westlake Avatar answered Jan 23 '26 21:01

Peter Westlake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!