django-avatar
django-avatar copied to clipboard
Non jpeg resized images can't be opened because of type mismatch
When resizing an image that is not of jpeg type (e.g. png or gif), the resulting image is converted into jpeg, but the extension is maintained from the original. The resulting image can't be opened as the extension does not match the real image type anymore.
After further investigation in the source code, I see that the problem is located in avatar_file_path()
method located in the models.py
file. There is a comment that explicitly says that using the file extension depends on whether AVATAR_HASH_FILENAMES
is activated or not, so if you don't set it to True explicitly in your settings.py the thumbnails will have the original extension, even they are in jpg. If you won't fix this, at least mention it in the docs, thanks! :)
def avatar_file_path(instance=None, filename=None, size=None, ext=None):
tmppath = [AVATAR_STORAGE_DIR]
if AVATAR_HASH_USERDIRNAMES:
tmp = hashlib.md5(get_username(instance.user)).hexdigest()
tmppath.extend([tmp[0], tmp[1], get_username(instance.user)])
else:
tmppath.append(get_username(instance.user))
if not filename:
# Filename already stored in database
filename = instance.avatar.name
if ext and AVATAR_HASH_FILENAMES:
# An extension was provided, probably because the thumbnail
# is in a different format than the file. Use it. Because it's
# only enabled if AVATAR_HASH_FILENAMES is true, we can trust
# it won't conflict with another filename
(root, oldext) = os.path.splitext(filename)
filename = root + "." + ext
else:
# File doesn't exist yet
if AVATAR_HASH_FILENAMES:
(root, ext) = os.path.splitext(filename)
filename = hashlib.md5(smart_str(filename)).hexdigest()
filename = filename + ext
if size:
tmppath.extend(['resized', str(size)])
tmppath.append(os.path.basename(filename))
return os.path.join(*tmppath)