开发者

Converting an UploadedFile to PIL image in Django

I'm trying to check an image's dimension, before saving it. I don't need to change it, just make sure it fits my limit开发者_如何转开发s.

Right now, I can read the file, and save it to AWS without a problem.

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},
        )

I need to put a step in the middle, that makes sure the file has the right size / width dimensions. My file isn't coming from a form that uses ImageField, and all the solutions I've seen use that.

Is there a way to do something like

img = Image.open(filedata)


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))


I've done this before but I can't find my old snippet... so here we go off the top of my head

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()


The code bellow creates the image from the request, as you want:

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜