jas*_*son 1 django django-models
Django新手:)
我通过包django- storage使用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")
Run Code Online (Sandbox Code Playgroud)
然后我决定在上传时调整图像大小,所以尝试在保存覆盖方法上添加以下代码...
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)
Run Code Online (Sandbox Code Playgroud)
这是问题,这给出了以下错误....
无法识别图像文件
然后我昨天在堆栈上发布了一个问题(我删除了)和一个用户链接到这个答案Django PIL:IOError无法识别我理解的图像文件(因为图像尚未上传它无法读取它).但我不确定这是我的问题!当我得到错误无法识别图像文件时,我可以看到原始文件实际上已经上传到S3 (当然没有调整大小).
记住我是新手,任何人都可以修改我的示例保存方法(和解释),以解决此问题的方法吗?即上传时将新图像重新调整为100x100的方法?
非常感谢
如果文件已经写好,请使用存储来读取文件然后调整大小....
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1025 次 |
| 最近记录: |