2011-09-23 62 views
5

我试图在保存图像之前检查图像的尺寸。我不需要改变它,只要确保它符合我的极限。在Django中将UploadedFile转换为PIL图像

现在,我可以读取该文件,并将其保存到AWS,而不会出现问题。

output['pic file'] = request.POST['picture_file'] 
conn = myproject.S3.AWSAuthConnection(aws_key_id, aws_key) 
filedata = request.FILES['picture'].read() 
content_type = 'image/png' 
conn.put(
     bucket_name, 
     request.POST['picture_file'], 
     myproject.S3.S3Object(filedata), 
     {'x-amz-acl': 'public-read', 'Content-Type': content_type}, 
     ) 

我需要在中间放一个步骤,确保文件具有正确的大小/宽度尺寸。我的文件不是来自使用ImageField的表单,我看到的所有解决方案都使用它。

有没有办法做这样的事情

img = Image.open(filedata) 

回答

1

我这样做过,但我无法找到我的旧片段...所以在这里我们去我的头离顶部

picture = request.FILES.get['picture'] 
img = Image.open(picture) 
#check sizes .... probably using img.size and then resize 

#resave if necessary 
imgstr = StringIO() 
img.save(imgstr, 'PNG') 
imgstr.reset() 

filedata = imgstr.read() 
+0

StringIO对象是我缺少的内存中暂时存储我的图像。谢谢! – Mashakal

3
image = Image.open(file) 
#To get the image size, in pixels.  
(width,height) = image.size() 
#check for dimensions width and height and resize 
image = image.resize((width_new,height_new)) 
+0

(width,height)= image.size not size() –

1

代码波纹管从请求创建图像,只要你想:

from PIL import ImageFile 
def image_upload(request): 
    for f in request.FILES.values(): 
     p = ImageFile.Parser() 
     while 1: 
      s = f.read(1024) 
      if not s: 
       break 
      p.feed(s) 
     im = p.close() 
     im.save("/tmp/" + f.name)