我正在尝试使用 PIL 调整图像大小,然后将其上传到 S3 存储桶。
模型形式工作得很好,除了图像大小调整没有发生。
以下是我的模型:
class ImageDetail(models.Model):
def upload_image(self, filename):
return u'obj/{name}.{ext}'.format(
name = uuid.uuid4().hex,
ext = os.path.splitext(filename)[1].strip('.')
)
flag = models.IntegerField(default=0)
view = models.IntegerField(default=0)
title = models.CharField(max_length=500, help_text="Enter a small/suitable title")
image = models.ImageField(upload_to = upload_image,
help_text="Please ensure, image size is less than 1 MB")
视图文件,如下所示:
form = ImageUploadForm(request.POST or None, request.FILES or None)
if form.is_valid() and request.POST:
form_instance = form.save(commit=False)
img = form_instance.image
# process the image now
if img.width > 300 or img.height > 200:
IMG_TYPE = os.path.splitext(img.name)[1].strip('.').lower()
if IMG_TYPE == 'jpeg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpeg'
elif IMG_TYPE == 'jpg':
PIL_TYPE = 'jpeg'
FILE_EXTENSION = 'jpeg'
elif IMG_TYPE == 'png':
PIL_TYPE = 'png'
FILE_EXTENSION = 'png'
elif IMG_TYPE == 'gif':
PIL_TYPE = 'gif'
FILE_EXTENSION = 'gif'
else:
print 'Not a valid format'
return
im = Image.open(StringIO(img.read()))
im.thumbnail((300, 180), Image.ANTIALIAS)
#Save the image
temp_handle = StringIO()
im.save(temp_handle, PIL_TYPE)
s3 = S3Custom()
if not form_instance.image:
return self.success(self.request, form, None, errors = 'Error while uploading the image')
form_instance.save()
S3自定义函数定义如下:
class S3Custom(object):
conn = S3Connection(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
b = Bucket(conn, settings.AWS_STORAGE_BUCKET_NAME)
k = Key(b)
def upload_file(self, ruta, prefix):
try:
self.k.key = '%s/%s' % (prefix, os.path.split(ruta)[-1])
self.k.set_contents_from_filename(ruta)
self.k.make_public()
except Exception, e:
print e
return '%s%s' % (settings.S3_URL, self.k.key)
我已经安装了django-storage
。问题是,图像上传得很好,但没有正确调整大小。我错过了什么?我错了吗
im.save(temp_handle, PIL_TYPE)
s3 = S3Custom()
form_instance.save()
在视图文件中?请让我知道,谢谢!