Reputation: 23
I'm pulling a JSON request of 20 random thumbnails to an iPhone application. At the moment I'm simply including the image thumb URLs in the JSON array (see below), then the iPhone goes out to get each image. This is really slow.
Original JSON Request:
{ "item_list": [ { "item_name": "Item One", "user_item_thumb": "http://localhost:8080/i/agpwaGluZ28tYXBwcg4LEghJdGVtVXNlchgPDA/67x67", }, { "item_name": "Item Two", "user_item_thumb": "http://localhost:8080/i/agpwaGluZ28tYXBwcg4LEghJdGVtVXNlchgQDA/67x67", }, { "item_name": "Item Three", "user_item_thumb": "http://localhost:8080/i/agpwaGluZ28tYXBwcg4LEghJdGVtVXNlchgRDA/67x67", } ] }
So, what I was thinking was using Base64 on the image data and actually including them in the JSON request, so the iPhone only needs one request instead of 21 requests. Make sense?
So, how do I do this?
I tried to simply print the below to JSON, but those are the full size images, I need to push a Base64 version of the Thumbnails.
Not working:
f = item.image
f_enc = f.encode('base64')
This is how I get my thumbs at the moment, just creating them on the fly.
http://localhost:8080/i/agpwaGluZ28tYXBwcg4LEghJdGVtVXNlchgSDA/67x67
This is what renders the above image request:
class Image(webapp.RequestHandler): def get(self, image_id): user = db.get(image_id) if user.image: picture = user.image self.response.headers['Content-Type'] = "image/png" self.response.out.write(picture) else: self.response.out.write("No image")
Any ideas would be amazing.
If there's a better way to do this, I'm all ears.
My problems:
- The iPhone is slow pulling in each of these 20 images
- The images are random, so caching is probably not an option.
- Is Base64 the way to go?
Thanks,
Danny
Upvotes: 2
Views: 1712
Reputation: 101149
Yes, encoding the images directly using base64 seems like a reasonable approach, given they're only thumbnails. This is similar to using data:
URLs in a webpage for the same reason.
Doing it should be as simple as calling the same Images API transforms you do in your regular code to generate the thumbnail, then serializing the resulting output as base64. You probably want to cache the result in memcache - in both handlers - to prevent redundant calls to the Images API. Alternately, you could calculate the thumbnail when the image is first uploaded, and store it alongside the full-size image.
Upvotes: 1
Reputation: 38382
Perhaps you just need to call read()
encoded = item.image.read().encode('base64')
If you're dealing with images of any great size, you'll want to encode in chunks (i.e. read(4096)
multiple times, encoding each piece).
Upvotes: 0