Created
December 24, 2015 02:27
-
-
Save lamarmarshall/95c09fded3eefc09c2c1 to your computer and use it in GitHub Desktop.
python django pillow thumbnail resize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment