我正在尝试调整图像大小,然后使用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()
在视图文件中? 请让我知道,谢谢!
答案 0 :(得分:0)
所以,首先要做的事情是:你几乎肯定不想同步调整大小 - 相反,启动Celery任务(或类似工具)以在保存原始文件后异步执行调整大小。
除此之外,你永远不会对s3
对象采取任何行动 - s3.upload_file
如果从未被调用过的话会做不了多少......
(我还建议使用某种静态分析器来警告你未使用的变量!)