Web2py中的图像缩略图:无法显示缩略图

时间:2015-06-26 22:35:14

标签: python image thumbnails web2py web2py-modules

我在这里使用了这个建议http://www.web2pyslices.com/slice/show/1387/upload-image-and-make-a-thumbnail 制作图像的缩略图。 我有缩略图,但我无法显示它。

以下是我的职能: db.py:

db.define_table('uploads', Field('dataset', 'reference dataset'),

Field('filename', represent = lambda x, row: "None" if x == None else [:45]),

Field('image', 'upload', uploadseparate=True, requires=IS_NOT_EMPTY() and IS_IMAGE(extensions=('jpeg', 'png','jpg','tif')) ),
Field('thumb', 'upload', uploadseparate=True, requires=IS_NOT_EMPTY() and IS_IMAGE(extensions=('jpeg', 'png', 'jpg', 'tif'))))

default.py:

def makeThumbnail(dbtable,ImageID,size=(150,150)):
    try:
       thisImage=db(dbtable.id==ImageID).select()[0]
       import os, uuid
       from PIL import Image
    except: return
    im=Image.open(request.folder + 'uploads/' + thisImage.image)
    im.thumbnail(size,Image.ANTIALIAS)
    thumbName='uploads.thumb.%s.jpg' % (uuid.uuid4())
    im.save(request.folder + 'uploads/' + thumbName,'jpeg')
    thisImage.update_record(thumb=thumbName)
    return


def insertImage():
    response.menu = [
    (T('Home'),False,URL('default','experimenter')),
    (T('Manage Data Set'),False,URL('default','MDS')),
    (T('Manage Experiment'),False,URL('default','ME')),
    (T('Manage Workflow Element'),False,URL('default','MWE'))]        
    dbtable = db.uploads 
    record = None
    record = db(db.dataset.id ==  request.args[0],ignore_common_filters=True).select().first()
    form = FORM(dbtable, INPUT(_name='up_files', _type='file',
    _multiple=True, requires=IS_NOT_EMPTY()),INPUT(_type='submit')) 
    # The multiple param lets us choose multiple files.
    if form.process().accepted:
    #onvalidation checks the uploaded files to make sure they are only txt,         config, or log.
    makeThumbnail(dbtable,form.vars.id,(300,300))
    response.flash = 'files uploaded' 
    files = request.vars['up_files'] 
       if not isinstance(files, list): 
    #convert files to a list if they are not one already.
        files = [files]
       for file in files:         
         db.uploads.insert(dataset=record.id, filename=file.filename, image=db.uploads.image.store(file, file.filename))

        #store is a FIELD method that let's you save a file to disk.  you can choose the directory if you want using the 'path' param.
    else:
        response.flash = 'Choose the Files you would like to upload'
   return dict(form=form, record=record)

然后是观点:

{{extend 'layout.html'}}
<h4>Manage Image of dataset: {{=record.name}}</h4>

{{if images:}}
<div style="overflow: auto;" width="80%">
<table>
<tr> <th> Image </th> </tr>
{{
    for image in images:
    =TR(TD(image.filename),  IMG(_src=URL('default', 'download',    args=image.thumb)), A(str(T('View')),_href=URL("show", args=[image.id,rowId])), A(str(T('Delete')),_href=URL('deleteImage',args=image.id)))}}
    {{pass}}
</table>

</div>
{{pass}}

注意:我正在尝试在图像列表中显示每个图像的缩略图。(请参阅视图)。 我没有得到缩略图,而是取而代之的是小问号。 PS:我无法上传图片。 我想用图像代替问号。我在insertImage()函数和视图中做错了。 在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

首先,您似乎正在混淆FORMSQLFORM。前者用于创建自定义表单(不与任何数据库表连接),后者用于基于数据库表构建表单(因此自动处理插入)。您不能像在代码中那样将DAL Table对象传递给FORM - 这将简单地将Table对象序列化为其字符串名称,该名称将包含在HTML表单DOM中以使其无效。此外,在这种情况下,form.vars.id将只是NoneFORM不会生成记录ID,因为它不会执行任何数据库插入。)

此外,不是直接在makeThumbnail中保存文件,更好的选择是将图像保存到StringIO对象,然后将该对象传递给db.uploads.thumbnail.store()(就像存储原始文件一样)图片)。在这种情况下,缩略图字段的.store()方法将自动处理文件命名和保存。

from cStringIO import StringIO
tmp = StringIO()
im.save(tmp, 'jpeg')
tmp.seek(0)
thisImage.update_record(thumb=db.uploads.thumb.store(tmp, filename='thumbnail.jpg'))

有关详细信息,请参阅http://web2py.com/books/default/chapter/29/06/the-database-abstraction-layer