I am overriding the save_model
method of modelAdmin to resize the image to 650 which is being uploaded via admin page:
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()
it is saving the image, but the image is broken, just a black image with "invalid image"
if I open it.
what am I doing wrong in above code?
I didnot know that PIL Images are of different type than Django ImageField type. Thanks to Skitz's answer , I could solve it this way:
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()
dont forget to do: import StringIO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.