未加星标

Django: Generating an Image with PIL

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二03 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

I've been reading through the Django Book , and in chapter 11 they talk about generating non-HTML content (such as PDF files, Images, RSS/Atom Feeds). They mention using PIL to generate images, but they don't give an example. So, I thought I'd post a simple example View that generates an image.

def pil_image(request):
''' A View that Returns a PNG Image generated using PIL'''
import Image, ImageDraw
size = (100,50) # size of the image to create
im = Image.new('RGB', size) # create the image
draw = ImageDraw.Draw(im) # create a drawing object that is
# used to draw on the new image
red = (255,0,0) # color of our text
text_pos = (10,10) # top-left position of our text
text = "Hello World!" # text to draw
# Now, we'll do the drawing:
draw.text(text_pos, text, fill=red)
del draw # I'm done drawing so I don't need this anymore
# We need an HttpResponse object with the correct mimetype
response = HttpResponse(mimetype="image/png")
# now, we tell the image to save as a PNG to the
# provided file-like object
im.save(response, 'PNG')
return response # and we're done!

This example just draws simple text, but the drawing code could be replaced by something more elaborate such as code that opens and scales existing images.

A note of concern: The Image object (im) MUST be saved as a PNG for this to work. Luckily, the Image.save method expects a file-like object as its first parameter, so we can use django's HttpResponse object here. Also, the example above doesn't make use of any particular Font for the drawing, so if you do want to draw text, you'll want to take a look at PIL's ImageDraw Documentation .

(on a side note: the html for the code above was generated using dpaste , which rocks!)

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: DjangoHTML
分页:12
转载请注明
本文标题:Django: Generating an Image with PIL
本站链接:http://www.codesec.net/view/479753.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(39)