我正在按照本教程上传(到 S3 Amazon)和使用 Django 操作图像。我被困在某个地方,因为我能够上传文件,但是每当调用应该创建拇指的方法时,我认为有些东西被遗漏了。
这是代码:
def upload_avatar_to(instance, filename):
import os
from django.utils.timezone import now
filename_base, filename_ext = os.path.splitext(filename)
return 'media/images/avatars/%s%s' % (
now().strftime("%Y%m%d%H%M%S"),
filename_ext.lower(),
)
class CustomUser(AbstractBaseUser, PermissionsMixin):
avatar = models.ImageField('profile picture', upload_to=upload_avatar_to, null=True, blank=True)
def save(self, *args, **kwargs):
super(CustomUser, self).save(*args, **kwargs)
self.create_avatar_thumb()
def create_avatar_thumb(self):
import os
from django.core.files.storage import default_storage as storage
if not self.avatar:
return ""
file_path = self.avatar.name
filename_base, filename_ext = os.path.splitext(file_path)
thumb_file_path = "%s_thumb.jpg" % filename_base
if storage.exists(thumb_file_path):
return "exists"
try:
f = storage.open(file_path, 'r')
image = Image.open(f)
width, height = image.size
if width > height:
delta = width - height
left = int(delta/2)
upper = 0
right = height + left
lower = height
else:
delta = height - width
left = 0
upper = int(delta/2)
right = width
lower = width + upper
image = image.crop((left, upper, right, lower))
image = image.resize((250, 250), Image.ANTIALIAS)
f_thumb = storage.open(thumb_file_path, "w")
image.save(f_thumb, "JPEG")
f_thumb.close()
return "success"
except:
return "error"
def get_avatar_thumb_url(self):
import os
from django.core.files.storage import default_storage as storage
if not self.avatar:
return ""
file_path = self.avatar.name
filename_base, filename_ext = os.path.splitext(file_path)
thumb_file_path = "%s_thumb.jpg" % filename_base
if storage.exists(thumb_file_path):
return storage.url(thumb_file_path)
return ""
看起来一切正常,但代码应该有问题。
我上传了图片,没有发现错误,但是:
- 图像没有调整大小
- 没有“avatar-name_thumb.jpg”创建并上传到存储桶
我能做什么?