lamarmarshall
12/24/2015 - 2:27 AM

python django pillow thumbnail resize

python django pillow thumbnail resize

MEDIA_ROOT = os.getcwd()+'/media/'
THUMBNAILS = MEDIA_ROOT+"thumbnails/"

             ct = request.FILES["file"].content_type
            ext = file_ext(ct)


            handle_uploaded_file(request.FILES['file'], generated_name+ext )
            thumbnail(MEDIA_ROOT+generated_name+ext, THUMBNAILS+generated_name+ext)


#functions

def thumbnail(infile, outfile):
    try:
        size=  128, 128
        img = Image.open(infile)
        img.load()
        img.thumbnail(size)
        img.save(outfile, "JPEG")
    except IOError :
        print("cannot create thumbnail for", infile)
        
def photo_count(username):
    return str(Photos.objects.filter(uid=username).count())


def generate_name():
    return str( uuid.uuid4() )

def file_ext( type ):
    if type == "image/png" :
        return ".png"
    if type == "image/jpeg" :
        return ".jpg"


def handle_uploaded_file(f, name):
    path = os.getcwd()
    with open(path+'/media/'+name, 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)