我遇到了从图像中获取额外调整大小的图像的问题。我正在使用django-cropper 0.1。 最初为裁剪图像建模的部分代码如下:
class Cropped(models.Model):
def __unicode__(self):
return u'%s-%sx%s' % (self.original, self.w, self.h)
def upload_image(self, filename):
return '%s/crop-%s' % (settings.ROOT, filename)
def save(self, *args, **kwargs): #force_insert=False, force_update=False, using=None):
source = self.original.image.path
target = self.upload_image(os.path.basename(source))
Image.open(source).crop([
self.x, # Left
self.y, # Top
self.x + self.w, # Right
self.y + self.h # Bottom
]).save(django_settings.MEDIA_ROOT + os.sep + target)
self.image = target
super(Cropped, self).save(*args, **kwargs)
但是我希望从裁剪后的图像中获得额外的调整大小的图像,所以我稍微更改了代码,现在它看起来像:
class Cropped(models.Model):
def __unicode__(self):
return u'%s-%sx%s' % (self.original, self.w, self.h)
def _get_average_path(self):
return _add_average(self.path)
average_path = property(_get_average_path)
def _get_average_url(self):
return _add_average(self.url)
average_url = property(_get_average_url)
def _get_large_path(self):
return _add_large(self.path)
large_path = property(_get_large_path)
def _get_large_url(self):
return _add_large(self.url)
large_url = property(_get_large_url)
def upload_image(self, filename):
return '%s/crop-%s' % (settings.ROOT, filename)
def save(self, *args, **kwargs): #force_insert=False, force_update=False, using=None):
source = self.original.image.path
target = self.upload_image(os.path.basename(source))
img = Image.open(source).crop([
self.x, # Left
self.y, # Top
self.x + self.w, # Right
self.y + self.h # Bottom
]).save(django_settings.MEDIA_ROOT + os.sep + target)
self.image = target
super(Cropped, self).save(*args, **kwargs)
img = Image.open(self.image.path)
img = img.resize((180, 180), Image.ANTIALIAS)
img.save(self.large_path, 'JPEG')
img = img.resize((104, 104), Image.ANTIALIAS)
img.save(self.average_path, 'JPEG')
但它仍在做基本工作。有人可以帮助我,并提出我应该在此代码中修复的内容的任何建议吗?
答案 0 :(得分:1)
我回答我自己的问题,因为我找到了解决方案,也许是某人。也许它现在是最好的解决方案,但它确实有效。首先,需要为额外的,已调整大小的图像添加其他字段:
average = models.ImageField(
blank=True, null=True,
verbose_name = _('Image'),
upload_to = upload_image,
editable = False,
)
然后需要将save()方法变为这样的东西:
def save(self, *args, **kwargs): #force_insert=False, force_update=False, using=None):
source = self.original.image.path
target = self.upload_image(os.path.basename(source))
Image.open(source).crop([
self.x, # Left
self.y, # Top
self.x + self.w, # Right
self.y + self.h # Bottom
]).save(django_settings.MEDIA_ROOT + os.sep + target)
self.image = target
splited_target = target.split("/")
avepath = "/average-".join(splited_target)
self.average = avepath
Image.open(self.image).resize((104, 104), Image.ANTIALIAS).save(django_settings.MEDIA_ROOT + avepath, 'JPEG')
super(Cropped, self).save(*args, **kwargs)
就是这样。