假设我有一个用于记录的图像的上传字段(如 - 个人资料图片),所以我的问题是我将如何更改该图片的格式? 我也很想使用PIL或PythonMagick API,但是我如何在Web2py中做到这一点?
答案 0 :(得分:1)
假设您有一个个人资料表和一个图片表 然后,您有一个控制器来编辑配置文件图像。 通过“改变图片的格式”,我想你想要调整图像大小,创建一个缩略图...... 以下是使用PIL的示例:
def edit_image():
"""
Edit a profile image, creates a thumb...
"""
thumb=""
profile = db.profile(request.vars.profile_id)
image = db(db.image.id==profile.image).select().first()
if image:
form = SQLFORM(db.image, image, deletable=True, showid=False)
thumb = image.thumb
else:
form = SQLFORM(db.image)
if form.accepts(request.vars, session):
response.flash = T('form accepted')
#resize the original image to a better size and create a thumbnail
__makeThumbnail(db.image,form.vars.id,(800,800),(260,260))
redirect(URL('images'))
elif form.errors:
response.flash = T('form has errors')
return dict(form=form,thumb=thumb)
以下是 __ makeThumbnail
的代码def __makeThumbnail(dbtable,ImageID,image_size=(600,600), thumbnail_size=(260,260)):
try:
thisImage=db(dbtable.id==ImageID).select()[0]
from PIL import Image
except: return
full_path = path.join(request.folder,'static','images', thisImage.file)
im = Image.open(full_path)
im.thumbnail(image_size,Image.ANTIALIAS)
im.save(full_path)
thumbName='thumb.%s' % (thisImage.file)
full_path = path.join(request.folder,'static','images', 'thumbs',thumbName)
try:
im.thumbnail(thumbnail_size,Image.ANTIALIAS)
except:
pass
im.save(full_path)
thisImage.update_record(thumb=thumbName)
return