我正在覆盖modelAdmin的save_model
方法,将图片大小调整为650,并通过管理页面上传:
def save_model(self, request, obj, form, change):
basewidth = 650
img = PIL.Image.open(form.cleaned_data['image_file'])
if img.size[0] > basewidth:
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
img_filefield = getattr(obj, 'image_file')
random_image_name = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(30)) + '.jpeg'
img.save(random_image_name)
img_filefield.save(random_image_name, ContentFile(img))
obj.save()
else:
obj.save()
它正在保存图像,但图像被破坏,如果我打开它,只有"invalid image"
的黑色图像。
我在上面的代码中做错了什么?
答案 0 :(得分:0)
我不知道PIL图像的类型与Django ImageField类型不同。感谢Skitz的answer,我可以这样解决:
def save_model(self, request, obj, form, change):
basewidth = 650
img = PIL.Image.open(form.cleaned_data['image_file'])
if img.size[0] > basewidth:
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), PIL.Image.ANTIALIAS)
img_file_lang = getattr(obj, 'image_file')
random_image_name = ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(30)) + '.jpeg'
image_io = StringIO.StringIO()
img.save(image_io, format='JPEG')
img_file_lang.save(random_image_name, ContentFile(image_io.getvalue()))
obj.save()
else:
obj.save()
别忘了这样做:import StringIO