Python 调整上载图像的大小无法正常工作Django
我有一个模型Python 调整上载图像的大小无法正常工作Django,python,django,django-models,django-forms,Python,Django,Django Models,Django Forms,我有一个模型 upload_path = 'images' upload_path_to_resize = 'resized' class Images(models.Model): image = models.ImageField(upload_to=upload_path, blank=True, null=True) image_url = models.URLField(blank=True, null=True) image_resized = model
upload_path = 'images'
upload_path_to_resize = 'resized'
class Images(models.Model):
image = models.ImageField(upload_to=upload_path, blank=True, null=True)
image_url = models.URLField(blank=True, null=True)
image_resized = models.ImageField(upload_to=upload_path_to_resize,blank=True)
width = models.PositiveIntegerField(null=True)
heigth = models.PositiveIntegerField(null=True)
def clean(self):
if (self.image == None and self.image_url == None ) or (self.image != None and self.image_url != None ):
raise ValidationError('Empty or both blanked')
def get_absolute_url(self):
return reverse('image_edit', args=[str(self.id)])
def save(self):
if self.image_url and not self.image:
name = str(self.image_url).split('/')[-1]
img = NamedTemporaryFile(delete=True)
img.write(urlopen(self.image_url).read())
img.flush()
self.image.save(name, File(img))
self.image_url = None
super(Images, self).save()
def resize(self):
if (self.width != None) or (self.heigth != None):
img = Image.open(self.image.path)
output_size = (self.width, self.heigth)
img.thumbnail(output_size)
img.save(self.image_resized.path)
super(Images, self).save()
resize方法应该从“ImageField”字段中获取现有文件,调整大小并加载到“image_resized”字段中,但是出于某种原因,FormResize表单将高度和宽度参数传递给模型,但什么也没有发生
from django.forms import ModelForm
from .models import Images
class ImageForm(ModelForm):
class Meta:
model = Images
fields = ['image', 'image_url']
class ResizedForm(ModelForm):
class Meta:
model = Images
fields = ['width', 'heigth']
我需要做什么才能正确调整大小?为什么不使用Django resized extension?它可以在上传时调整你的文件大小。它可以为你做所有的事情,甚至更多
调整大小功能未正确保存调整大小的输出 尝试: 保存调整大小的_图像时,需要传入文件名和将要存储的二进制对象,而不仅仅是路径 如果执行此操作,您将不需要super().save()调用,因为您正在resize函数中保存已调整大小的_图像字段
我还没有测试过这段代码,可能会给它一个注释,但它太长了。我需要自己做这件事。在这种情况下,尝试阅读django resized app的代码,它会给你一些提示;)我明白,但我的头脑已经沸腾了,我无法充分感知信息,我想重新审视一下,并就如何更正代码提出建议欢迎来到StackOverflow!虽然这可以回答这个问题,但在这里包括答案的基本部分,并提供链接供参考。事实上,如果type(img)是File,那么您可以跳过img.save()行,只需将img作为第二个参数传递给self.resized_image.save(),非常感谢,有一个问题是img.save('/tmp/some/temporary/path.png'))我需要把我的上传路径或什么?你能评论最后2行吗?我复制了你的代码,但没有真正检查它,我已经编辑了我的答案。这次它不是保存到临时文件,而是保存到内存中的文件,然后再保存到大小调整后的图像字段。非常感谢,它可以工作。最后一个问题,如何使我不仅可以改变宽度和高度,而且可以分别改变?如果答案有效,请为将来的读者标记为正确。我将您的问题解释为询问如何仅更改高度或宽度,您可以使用django.core.files.images import get_image_dimensions获取原始图像尺寸,然后使用
width,height=get_image_dimensions(self.image.file)
重构您的大小调整函数。
from django.core.files import File
import os.path
from PIL import Image
from io import BytesIO
from django.core.files.base import ContentFile
def resize(self):
if self.width and self.heigth:
img = Image.open(self.image)
output_size = (self.width, self.heigth)
img.thumbnail(output_size)
thumb_name, thumb_extension = os.path.splitext(self.image.name)
thumb_extension = thumb_extension.lower()
thumb_filename = thumb_name + '_thumb' + thumb_extension
if thumb_extension in ['.jpg', '.jpeg']:
FTYPE = 'JPEG'
elif thumb_extension == '.gif':
FTYPE = 'GIF'
elif thumb_extension == '.png':
FTYPE = 'PNG'
else:
return False # Unrecognized file type
# Save thumbnail to in-memory file as StringIO
temp_thumb = BytesIO()
img.save(temp_thumb, FTYPE)
temp_thumb.seek(0)
self.image_resized.save(thumb_filename, ContentFile(temp_thumb.read()))
temp_thumb.close()