Louis Sayers
Louis Sayers

Reputation: 2219

How do you store an app engine Image object in the db?

I'm a bit stuck with my code:

def setVenueImage(img):
  img = images.Image(img.read())
  x, y = photo_utils.getIdealResolution(img.width, img.height)
  img.resize(x, y)
  img.execute_transforms()
  venue_obj = getVenueSingletonObject()
  if venue_obj is None:
      venue_obj = Venue(images = [img])
  else:
      venue_obj.images.append(img)
  db.put(venue_obj)

I'm using django with app engine - so img.read() works fine.

In fact all of this code works fine up until I try to store img into the database. My model expects a Blob, so when I put in the image as img, then it throws a fit, and I get:

BadValueError at /admin/venue/ Items in the images list must all be Blob instances

Ok, so an Image must not be a Blob, but then how do I make it a blob? Blobs take in a byte string, but how do I make my image a byte string?

I haven't seen in the docs anywhere where they actually use image objects, so I'm not sure how this is all supposed to work, but I do want to use image objects to resize my image (I know you can do it in PIL, but I'd like to know how to do it with google's Image class).

Thanks for any pointers :)

Upvotes: 1

Views: 2123

Answers (3)

Joe Beda
Joe Beda

Reputation: 2761

This will probably work:

def setVenueImage(img):
  img = images.Image(img.read())
  x, y = photo_utils.getIdealResolution(img.width, img.height)
  img.resize(x, y)
  img_bytes = img.execute_transforms() # Converts to PNG
  venue_obj = getVenueSingletonObject()
  if venue_obj is None:
      venue_obj = Venue(images = [img_bytes])
  else:
      venue_obj.images.append(img_bytes)
  db.put(venue_obj)

I'm assuming that Venue.images is a ListProperty(db.Blob), correct? This is probably the wrong thing to do. Define a VenueImage model with a simple blob property and store its key into the Venue. If you put the images in there directly you'll hit the 1MB row limit on the datastore.

Upvotes: 2

Louis Sayers
Louis Sayers

Reputation: 2219

I'm not happy with this solution as it doesn't convert an Image object to a blob, but it will do for the time being:

def setVenueImage(img):
  original = img.read()
  img = images.Image(original)
  x, y = photo_utils.getIdealResolution(img.width, img.height)
  img = images.resize(original, x, y)
  venue_obj = getVenueSingletonObject()
  if venue_obj is None:
      venue_obj = Venue(images = [db.Blob(img)])
  else:
      venue_obj.images.append(db.Blob(img))
  db.put(venue_obj)

Upvotes: 2

airportyh
airportyh

Reputation: 22668

http://code.google.com/appengine/docs/python/images/usingimages.html

I think that link should help. Good luck.

Upvotes: 0

Related Questions