在Django上传图像后如何轻松调整图像大小?我正在使用Django 1.0.2,我已经安装了PIL.
我正在考虑重写模型的save()方法来调整它的大小,但我真的不知道如何开始并覆盖它.
有人能指出我正确的方向吗?谢谢 :-)
@GuðmundurH:这不行,因为django-stdimage包在Windows上不起作用:-(
我建议使用django-stdimage中的StdImageField,它应该为你处理所有脏工作.它易于使用,您只需在字段定义中指定已调整大小的图像的尺寸:
class MyModel(models.Model): image = StdImageField(upload_to='path/to/img', size=(640, 480))
查看文档 - 它也可以做缩略图.
您应该使用一种方法来处理上传的文件,如Django文档中所示.
在此方法中,您可以在变量中连接块(而不是直接将它们写入磁盘),从该变量创建PIL图像,调整图像大小并将其保存到磁盘.
在PIL中,你应该看看Image.fromstring
和Image.resize
.
我使用此代码处理上传的图像,在内存上调整它们的大小(不将它们永久保存在磁盘上),然后将拇指保存在Django ImageField上.希望可以帮助.
def handle_uploaded_image(i): import StringIO from PIL import Image, ImageOps import os from django.core.files import File # read image from InMemoryUploadedFile image_str = “” for c in i.chunks(): image_str += c # create PIL Image instance imagefile = StringIO.StringIO(image_str) image = Image.open(imagefile) # if not RGB, convert if image.mode not in (“L”, “RGB”): image = image.convert(“RGB”) #define file output dimensions (ex 60x60) x = 130 y = 130 #get orginal image ratio img_ratio = float(image.size[0]) / image.size[1] # resize but constrain proportions? if x==0.0: x = y * img_ratio elif y==0.0: y = x / img_ratio # output file ratio resize_ratio = float(x) / y x = int(x); y = int(y) # get output with and height to do the first crop if(img_ratio > resize_ratio): output_width = x * image.size[1] / y output_height = image.size[1] originX = image.size[0] / 2 - output_width / 2 originY = 0 else: output_width = image.size[0] output_height = y * image.size[0] / x originX = 0 originY = image.size[1] / 2 - output_height / 2 #crop cropBox = (originX, originY, originX + output_width, originY + output_height) image = image.crop(cropBox) # resize (doing a thumb) image.thumbnail([x, y], Image.ANTIALIAS) # re-initialize imageFile and set a hash (unique filename) imagefile = StringIO.StringIO() filename = hashlib.md5(imagefile.getvalue()).hexdigest()+’.jpg’ #save to disk imagefile = open(os.path.join(‘/tmp’,filename), ‘w’) image.save(imagefile,’JPEG’, quality=90) imagefile = open(os.path.join(‘/tmp’,filename), ‘r’) content = File(imagefile) return (filename, content) #views.py form = YourModelForm(request.POST, request.FILES, instance=profile) if form.is_valid(): ob = form.save(commit=False) try: t = handle_uploaded_image(request.FILES[‘icon’]) ob.image.save(t[0],t[1]) except KeyError: ob.save()
我强烈推荐使用sorl-thumbnail应用程序轻松,透明地处理图像大小调整.它开始于我开始的每一个Django项目.