<s> from django import template <EOL> from django . conf import settings <EOL> register = template . Library ( ) <EOL> @ register . filter <EOL> def thumbnail ( url , size = '<STR_LIT>' ) : <EOL> """<STR_LIT>""" <EOL> import os <EOL> if url . startswith ( settings . MEDIA_URL ) : <EOL> url = url [ len ( settings . MEDIA_URL ) : ] <EOL> original_path = settings . MEDIA_ROOT + url <EOL> try : <EOL> basename , format = original_path . rsplit ( '<STR_LIT:.>' , <NUM_LIT:1> ) <EOL> except ValueError : <EOL> return os . path . join ( settings . MEDIA_URL , url ) <EOL> thumbnail = basename + '<STR_LIT>' + size + '<STR_LIT:.>' + format <EOL> thumbnail_url = '<STR_LIT>' % ( settings . MEDIA_URL , thumbnail [ len ( settings . MEDIA_ROOT ) : ] ) <EOL> if not os . path . exists ( thumbnail ) : <EOL> import Image <EOL> try : <EOL> image = Image . open ( original_path ) <EOL> except IOError : <EOL> return os . path . join ( settings . MEDIA_URL , url ) <EOL> original_image = image . copy ( ) <EOL> original_width = original_image . size [ <NUM_LIT:0> ] <EOL> original_height = original_image . size [ <NUM_LIT:1> ] <EOL> try : <EOL> desired_width , desired_height = [ int ( x ) for x in size . split ( '<STR_LIT:x>' ) ] <EOL> new_size = ( desired_width , desired_height ) <EOL> crop = True <EOL> except ValueError : <EOL> if size [ <NUM_LIT:0> ] == '<STR_LIT:x>' : <EOL> desired_height = int ( size [ <NUM_LIT:1> : ] ) <EOL> new_size = ( original_width , desired_height ) <EOL> crop = False <EOL> else : <EOL> desired_width = int ( size ) <EOL> new_size = ( desired_width , original_height ) <EOL> crop = False <EOL> if crop : <EOL> if ( original_height / ( original_width / float ( desired_width ) ) ) < desired_height : <EOL> image . thumbnail ( ( original_width , desired_height ) , Image . ANTIALIAS ) <EOL> else : <EOL> image . thumbnail ( ( desired_width , original_height ) , Image . ANTIALIAS ) <EOL> if ( image . size [ <NUM_LIT:0> ] >= desired_width ) and ( image . size [ <NUM_LIT:1> ] >= desired_height ) : <EOL> left = ( image . size [ <NUM_LIT:0> ] - desired_width ) / <NUM_LIT:2> <EOL> top = ( image . size [ <NUM_LIT:1> ] - desired_height ) / <NUM_LIT:2> <EOL> right = left + desired_width <EOL> bottom = top + desired_height <EOL> cropped_image = image . crop ( ( left , top , right , bottom ) ) <EOL> image = cropped_image <EOL> else : <EOL> image . thumbnail ( new_size , Image . ANTIALIAS ) <EOL> try : <EOL> image . save ( thumbnail , image . format , quality = <NUM_LIT> ) <EOL> except KeyError : <EOL> return '<STR_LIT>' <EOL> return thumbnail_url </s>
