我正在尝试这段代码,但是做错了。
class Photo(TimestampedModel):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
image = models.ImageField(upload_to="photos")
image_600 = ImageSpecField(source='image',
processors=[ResizeToFill(600, 600)],
format='JPEG',
options={'quality': 70})
def save(self, *args, **kwargs):
if not self.id:
self.image = self.compressImage(self.image)
super(Photo, self).save(*args, **kwargs)
def compressImage(self, image):
imageTemporary = Image.open(image)
format = imageTemporary.format
outputIoStream = BytesIO()
imageTemporary.save(outputIoStream, format=format, quality=70)
outputIoStream.seek(0)
image = InMemoryUploadedFile(outputIoStream, 'ImageField', image.name,
format, None, None)
return image
def resizeImage(self, image):
basewidth = 600
img = Image.open(image)
format = img.format
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIALIAS)
outputIoStream = BytesIO()
img.save(outputIoStream, format=format, quality=70)
outputIoStream.seek(0)
image = InMemoryUploadedFile(outputIoStream, 'ImageField', image.name,
format, None, None)
return image
该想法是创建具有新大小的第二个图像(image_card
)。
最后,我得到的是image_card
的图像,而不是image
的图像。
方法compressImage()
和resizeImage()
正常工作,但是我怀疑resizeImage正在获取相同的图像实例。
如果我对line self.image_card = self.resizeImage(self.image)
进行评论,则image
将再次起作用。