Skip to content

Instantly share code, notes, and snippets.

@johnschimmel
Created February 6, 2013 23:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save johnschimmel/4726730 to your computer and use it in GitHub Desktop.
Save johnschimmel/4726730 to your computer and use it in GitHub Desktop.
AppEngine upload, combine images and save to blob store. Python PIL and PIL paste function to give uploaded image a background
# -*- coding: utf-8 -*-
"""
A real simple app for using webapp2 with auth and session.
It just covers the basics. Creating a user, login, logout
and a decorator for protecting certain handlers.
Routes are setup in routes.py and added in main.py
"""
# standard library imports
from __future__ import with_statement
import logging
import re
import json
import urllib
import datetime
import hashlib
import uuid
import os
import StringIO
# related third party imports
import webapp2
import httpagentparser
from webapp2_extras import security
from webapp2_extras.auth import InvalidAuthIdError, InvalidPasswordError
from webapp2_extras.i18n import gettext as _
from webapp2_extras.appengine.auth.models import Unique
from google.appengine.api import urlfetch
from google.appengine.api import taskqueue
from google.appengine.api import app_identity
from google.appengine.api import app_identity
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
from google.appengine.api import images
from PIL import Image
# local application/library specific imports
import models
import forms as forms
from lib.basehandler import BaseHandler
from google.appengine.ext import ndb
from dateutil.relativedelta import relativedelta
from app import base_config
from google.appengine.api import files
class HelloWorldHandler(BaseHandler):
def get(self):
templateData = {
'upload_path' : blobstore.create_upload_url('/upload-test')
}
return self.render_template("/uploadtest.html", **templateData)
# data = {
# 'status' : 'OK',
# 'form_post_url' : blobstore.create_upload_url('/upload-test')
# }
# return sendJSONresponse(self.response, data, self.request.GET.get('callback'))
class UploadTestHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
uploaded_image = self.get_uploads('image') # 'image' is the file form field name
if len(uploaded_image) == 1:
# upload profile
blob_info = uploaded_image[0]
if blob_info.size > 0:
logging.info(blob_info)
image_url = images.get_serving_url(blob_info.key(), size=None, crop=False, secure_url=None)
image_w_bg = addBackground(blob_info.key())
# self.response.headers['Content-Type'] = "image/png"
# self.response.out.write(image_w_bg)
if image_w_bg:
# Create the file
file_name = files.blobstore.create(mime_type='application/octet-stream')
# Open the file and write to it
with files.open(file_name, 'a') as f:
f.write(image_w_bg) #image_w_bg.tostring('raw'))
# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Get the file's blob key
new_blob_key = files.blobstore.get_blob_key(file_name)
output = images.get_serving_url(new_blob_key, size=None, crop=False, secure_url=None)
logging.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$")
logging.info(output)
self.redirect(str(output))
else:
# no image uploaded, must delete the blob that was allocated by GAE #weirdappenginething
blob_info.delete()
logging.info("deleting blob")
return self.response.write("no image uploaded")
'''adds a white background 1400x900'''
def addBackground(blob_key):
# try:
blob_reader = blobstore.BlobReader(blob_key)
img = Image.open(blob_reader)
logging.info("inside addBackground")
logging.info(img)
logging.info("******************************************")
img_w,img_h=img.size
background = Image.new('RGBA', (1440,900), (255, 255, 255, 255))
bg_w,bg_h=background.size
offset=((bg_w-img_w)/2,(bg_h-img_h)/2)
background.paste(img,offset)
output = StringIO.StringIO()
background.save(output, format="png")
background_data = output.getvalue()
output.close()
return background_data
# except:
# logging.error("unable to out 'img' passed into addBackground")
# return None
def sendJSONresponse(response, data, callback, httpcode=200):
jsonp_callback = callback
if jsonp_callback:
response.headers['Content-Type'] = 'application/javascript'
response_data = jsonp_callback + "(" + json.dumps(data) + ")"
else:
response.headers['Content-Type'] = 'application/json'
response_data = json.dumps(data)
response.status = httpcode
return response.write(response_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment