开发者

Django - Saving thumbnail with different filename

I want to create thumbnails of uploaded image files and save them with "_th" at the end of the filename. Currently, I am using the following code:

def _create_thumbnail(img_path):
    image = Image.open(img_path)

    if image.mode not in ("L", "RGB"):
        image = image.convert("RGB")

    image.thumbnail(MEDIA_THUMBNAIL_SIZES, Image.ANTIALIAS)
    return image.save(img_path, 'JPEG', quality=MEDIA_THUMBNAIL_QUALITY)

It overwrites the original file. Is there a way to easily change the name of the file to include _th before the file extension and save it in the same place?

Also, I am saving the thumbnail after the post save signal using the following method:

@receiver(post_save, sender=Media, dispatch_uid="media_create_thumb")
def create_media_thumbnail(sender, **kwargs):
    thumb = generate_thumbnail(kwargs['instance'].file)

I was wondering if this is an ok (pythonic?) way of using signals? Since I am not using the django admin panel, using the admins post save isn't an option.

This method to create thumbnails will be open to users, so if there is anything about the above code which might cause problems, I'd appreciate the heads开发者_开发问答 up!


I would try the following:

import os

(head, tail) = os.path.split(img_path)
(name,ext)=tail.split('.')
tail=name+'_th.'+ext
img_path=os.path.join(head,tail)

edit: as i found out recently, you can even shortcut that:

(name,ext)=os.path.splitext(img_path)
img_path = name + '_th.' + ext
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜