Reputation: 776
I'm trying to overlay some text over an image on GAE. Now they expose the PIL library it should not be problem.
Here's what I have. It works, but I can't help think I should be writing directly to the background image rather than creating a separate overlay image and then merging.
Can I use Image.frombuffer or something, I've given it a go but I'm just not getting it...
from PIL import Image, ImageDraw, ImageFont
from google.appengine.api import images
from google.appengine.ext import blobstore
from google.appengine.api import files
def compose(key):
# create new image
text_img = Image.new('RGBA', (800,600), (0, 0, 0, 0))
draw = ImageDraw.Draw(text_img)
draw.text((0, 0), 'HELLO TEXT', font=ImageFont.load_default())
# no write access on GAE
output = StringIO.StringIO()
text_img.save(output, format="png")
text_layer = output.getvalue()
output.close()
# read background image
blob_reader = blobstore.BlobReader(key)
background = images.Image(blob_reader.read())
# merge
merged = images.composite([(background, 0, 0, 1.0, images.TOP_LEFT),
(text_layer, 0, 0, 1.0, images.TOP_LEFT)],
800, 600)
# save
file_name = files.blobstore.create(mime_type='image/png')
with files.open(file_name, 'a') as f:
f.write(merged)
files.finalize(file_name)
Upvotes: 3
Views: 2015
Reputation: 8199
You should use the [Image.open][1]
method instead. Image.frombuffer
and Image.fromstring
decode pixel data not raw images.
In your case you could use something like:
blob_reader = blobstore.BlobReader(key)
text_img = Image.open(blob_reader)
.........
Upvotes: 2
Reputation: 16882
You need to open the image with PIL, not the app engine image type (another answer was off by one character: Image
, not Images
):
blob_reader = blobstore.BlobReader(key)
text_img = Image.open(blob_reader)
Upvotes: 2
Reputation: 308392
To draw directly on the background image would be the most straightforward:
draw = ImageDraw.Draw(background)
draw.text((0, 0), 'HELLO TEXT', font=ImageFont.load_default())
Upvotes: 0