Python论坛  - 讨论区

标题:[python-chinese] [django] PIL图片缩略代码

2006年10月09日 星期一 19:28

风向标 vaneoooo在gmail.com
星期一 十月 9 19:28:18 HKT 2006

×Ô¼ºÐ´µÄ£¬ºÃÏñÒ²ÓÐÐÖµÜÐèÒª£¬´úÂëºÜ³ó¡£²îµÄºÜ£¬´ó¼ÒÅúÆÀ¡£

ÒÔÏ´úÂëµ¥¶ÀΪһ¸öÎļþ£¬ÓëdjangoÅäºÏ£¬Éú³ÉËõÂÔͼ¡£

#coding=utf-8

import Image
import os
import StringIO
from APPSname.settings import DEFAULT_IMAGE

def cropimage(image,width,height):

    x = width - height
    if x>0:
        t = x/2
        image = image.crop((t,0,height+t,height))
    if x<0:
        t = abs(x)/2
        image = image.crop((0,t,width,width+t))
    return image

def pastetuple(width,height,arg):
    w , h = 0 , 0
    if width < arg:
        w = (arg - width)/2
    if height < arg:
        h = (arg - height)/2
    tu = (w,h)
    return tu

def thumbnail(content,arg):
    size = (arg,arg)
    im = StringIO.StringIO(content)
    image = Image.open(im)
    image = image.convert('RGB')
    width,height = image.size
    if width > arg or height > arg:
        image = cropimage(image,width,height)

    image.thumbnail(size,Image.ANTIALIAS)
    width,height = image.size
    if width < arg or height < arg:
        tu = pastetuple(width,height,arg)
        bg = Image.open(DEFAULT_IMAGE)
        bg.paste(image,tu)
        image = bg

    buf = StringIO.StringIO()
    image.save(buf, "JPEG")
    return buf.getvalue()
-------------- 下一部分 --------------
Ò»¸öHTML¸½¼þ±»ÒƳý...
URL: http://python.cn/pipermail/python-chinese/attachments/20061009/67430629/attachment.html 

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

2006年10月09日 星期一 19:59

symbol lendcomcn在gmail.com
星期一 十月 9 19:59:14 HKT 2006

谢谢风兄的分享,稍加改造了一下,分享如下:

from PIL import Image
import os.path

def cropimage(image,width,height):

    x = width - height
    if x>0:
        t = x/2
        image = image.crop((t,0,height+t,height))
    if x<0:
        t = abs(x)/2
        image = image.crop((0,t,width,width+t))
    return image

def thumbnail(filename, size=(48,48), thumbnail_filename=None):
    image = Image.open(filename)
    image = image.convert('RGB')

    width,height = image.size
    if width > size[0] or height >size[1]:
        image = cropimage(image,width,height)

    image.thumbnail(size, Image.ANTIALIAS)


    if not thumbnail_filename:
        thumbnail_filename = get_default_thumbnail_filename(filename)

    #image.resize((size),
Image.ANTIALIAS).save(file(thumbnail_filename, 'wb'), "JPEG")
    image.save(file(thumbnail_filename, 'wb'), "JPEG")

    return thumbnail_filename


def get_default_thumbnail_filename(filename):
    path, ext = os.path.splitext(filename)
    return path + ext

[导入自Mailman归档:http://www.zeuux.org/pipermail/zeuux-python]

如下红色区域有误,请重新填写。

    你的回复:

    请 登录 后回复。还没有在Zeuux哲思注册吗?现在 注册 !

    Zeuux © 2025

    京ICP备05028076号