Django新手:)
我通过包django-storages使用 S3存储。当我通过管理员上传/更新新图像时,这看起来很完美。
models.py (图片字段)
image = models.ImageField(
upload_to=path_and_rename("profiles"),
height_field="image_height",
width_field="image_width",
null=True,
blank=True,
editable=True,
help_text="Profile Picture",
verbose_name="Profile Picture"
)
image_height = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
image_width = models.PositiveIntegerField(null=True, blank=True, editable=False, default="100")
然后我决定在上传时调整图像大小,所以尝试在保存覆盖方法上添加以下代码...
def save(self, *args, **kwargs):
if not self.id and not self.image:
return
super(Profile, self).save(*args, **kwargs)
image = Image.open(self.image).seek(0)
(width, height) = image.size
size = ( 100, 100)
image = image.resize(size, Image.ANTIALIAS)
image.save(self.image.path)
这是问题,这给出了以下错误....
无法识别图片文件
然后我昨天在堆栈上发布了一个问题(我删除了)和一个链接到这个答案Django PIL : IOError Cannot identify image file的用户我理解了(因为图片没有上传它无法读取它)然而)。 但我不确定这是我的问题!当我收到错误无法识别图片文件时,我可以看到原始文件实际上已上传到S3 (当然没有调整大小)。
记住我是新手任何人都可以修改我的示例保存方法(并解释)以解决此问题的方法吗?即在上传时将新图像重新调整为100x100的方法?
非常感谢
答案 0 :(得分:6)
如果文件已经写好,请使用存储空间来读取文件然后调整大小....
def save(self, *args, **kwargs):
if not self.id and not self.image:
return
super(Profile, self).save(*args, **kwargs)
import urllib2 as urllib
from cStringIO import StringIO
from django.core.files.uploadedfile import SimpleUploadedFile
'''Open original photo which we want to resize using PIL's Image object'''
img_file = urllib.urlopen(self.image.url)
im = StringIO(img_file.read())
resized_image = Image.open(im)
'''Convert to RGB if necessary'''
if resized_image.mode not in ('L', 'RGB'):
resized_image = resized_image.convert('RGB')
'''We use our PIL Image object to create the resized image, which already
has a thumbnail() convenicne method that constrains proportions.
Additionally, we use Image.ANTIALIAS to make the image look better.
Without antialiasing the image pattern artificats may reulst.'''
resized_image.thumbnail((100,100), Image.ANTIALIAS)
'''Save the resized image'''
temp_handle = StringIO()
resized_image.save(temp_handle, 'jpeg')
temp_handle.seek(0)
''' Save to the image field'''
suf = SimpleUploadedFile(os.path.split(self.image.name)[-1].split('.')[0],
temp_handle.read(), content_type='image/jpeg')
self.image.save('%s.jpg' % suf.name, suf, save=True)
答案 1 :(得分:0)
如果您希望
image.save(self.image.path)
上班。你不应该用
打开它image = Image.open(self.image.path).seek(0)