Monday, 15 July 2013

Django Python PIL save image - broken image -



Django Python PIL save image - broken image -

i overriding save_model method of modeladmin resize image 650 beingness 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) _ in range(30)) + '.jpeg' img.save(random_image_name) img_filefield.save(random_image_name, contentfile(img)) obj.save() else: obj.save()

it saving image, image broken, black image "invalid image" if open it.

what doing wrong in above code?

i didnot know pil images of different type django imagefield type. skitz's answer, solve 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) _ 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 do: import stringio

python django image python-imaging-library

No comments:

Post a Comment