1 from django.conf import settings
5 def make_thumbnail(imagefile,width=None,height=None):
6 # first check that the thumbnail image doesn't already exist
7 # and if it does that it's newer than the origional image
9 base_dir = settings.MEDIA_ROOT
11 if not thumbs_dir.endswith("/"):
12 thumbs_dir = "%s/" %(thumbs_dir,)
13 base_dir = "%s/" %(base_dir,)
16 thumbs_dir = "%s%s/" %(thumbs_dir, settings.THUMBS_DIRECTORY)
17 thumbsdirectory = settings.THUMBS_DIRECTORY
19 thumbs_dir = "%sthumbs/" %(thumbs_dir,)
20 thumbsdirectory = "thumbs"
24 thumb = os.stat("%sw%d/%s" % (thumbs_dir, width, imagefile))
25 pic = os.stat("%s%s" % (base_dir, imagefile))
26 if thumb.st_ctime < pic.st_ctime:
28 img = Image.open("%s%s" %(base_dir, imagefile))
29 (curwidth,curheight) = img.size
32 newheight = int((newwidth * curheight) / curwidth)
34 newimg = img.resize((newwidth, newheight))
35 newimg.save("%sw%d/%s" %(thumbs_dir, width, imagefile))
37 return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
40 return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
42 # well, there's not one there. feh. sucks.
44 directory_to_create = imagefile[:imagefile.rindex(os.sep)]
45 img = Image.open("%s%s" %(base_dir, imagefile))
46 if not os.path.isdir("%sw%d/%s" %(thumbs_dir, width, directory_to_create)):
47 os.makedirs("%sw%d/%s" %(thumbs_dir, width, directory_to_create))
48 (curwidth,curheight) = img.size
51 newheight = int((newwidth * curheight) / curwidth)
53 newimg = img.resize((newwidth, newheight))
54 newimg.save("%sw%d/%s" %(thumbs_dir, width, imagefile))
56 return "%s%s/w%d/%s" %(settings.MEDIA_URL, thumbsdirectory, width, imagefile)
58 sys.stderr.write("Got exception: %s" %(e,))
62 thumb = os.stat("%sh%d/%s" % (thumbs_dir, height, imagefile))
63 pic = os.stat("%s%s" % (base_dir, imagefile))
64 if thumb.st_ctime < pic.st_ctime:
66 img = Image.open("%s%s" %(base_dir, imagefile))
67 (curwidth,curheight) = img.size
70 newheight = int((newheight * curwidth) / curheight)
72 newimg = img.resize((newwidth, newheight))
73 newimg.save("%sh%d/%s" %(thumbs_dir, height, imagefile))
75 return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
78 return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
80 # well, there's not one there. feh. sucks.
82 directory_to_create = imagefile[:imagefile.rindex(os.sep)]
83 img = Image.open("%s%s" %(base_dir, imagefile))
84 os.makedirs("%sh%h/%s" %(thumbs_dir, height, directory_to_create))
85 (curwidth,curheight) = img.size
88 newwidth = int((newheight * curwidth) / curheight)
90 newimg = img.resize((newwidth, newheight))
91 newimg.save("%sh%d/%s" %(thumbs_dir, height, imagefile))
93 return "%s%s/h%d/%s" %(settings.MEDIA_URL, thumbsdirectory, height, imagefile)
97 # if everything fails, we'll return the origional image URL
98 # this is for simpilicity
99 return "%s%s" %(settings.MEDIA_URL, imagefile)