Image resizing

50 views
Skip to first unread message

akash...@ranosys.com

unread,
Mar 24, 2015, 6:07:06 AM3/24/15
to django...@googlegroups.com
Hi..
can anyone please tell me how to resize the uploaded image....
This is my model
class User(models.Model):
    first_name=models.CharField(
verbose_name = "First Name *",max_length=20,blank=False)
    last_name=models.CharField(verbose_name = "Last Name *",max_length=20,blank=False)
    username=models.EmailField(verbose_name = "Email *",max_length=30,blank=False)
    password=models.CharField(verbose_name = "Password *",max_length=15,blank=False)
    dob=models.DateField(verbose_name = "DOB *" ,blank=True,null=True)
    mobileno=models.CharField(verbose_name = "Mobile No *",max_length=20,blank=False)
    houseno=models.CharField(verbose_name = "House No",max_length=10,blank=True)
    address1=models.CharField(verbose_name = "Adress1",max_length=30,blank=True)
    city=models.CharField(verbose_name = "City",max_length=20,blank=True)
    state=models.CharField(verbose_name = "State",max_length=30,blank=True)
    pincode=models.CharField(verbose_name = "Pincode",max_length=20,blank=True)
    country=models.CharField(verbose_name = "Country",max_length=30,blank=True)
    comment=models.CharField(verbose_name = "Comment",max_length=200,blank=True)
    sex=models.CharField(verbose_name = "Sex *",max_length=5,blank=False)
    image=models.FileField(verbose_name = "Image(limit 1Mb) *",blank=True,upload_to='media/')
   
    def __unicode__(self):
        return self.first_name


this is my form
class Registration(forms.ModelForm):
      password = forms.CharField(label='Password *',widget=forms.PasswordInput())
      image = forms.ImageField(label='Select a file *',help_text='max. 1 megabytes')
      class Meta:

view.py
def registration(request):
    #request.session.set_test_cookie()
    if request.method == "POST":
            regform=Registration(request.POST,request.FILES)
            if regform.is_valid():
               #item=resize_and_crop(img_path, modified_path, size, crop_type='top')
               regform.save();
               return HttpResponseRedirect('/login/')
               
            else:
                return render_to_response('registration.html',{"form":regform})
    else:
        regform=Registration()
    return render_to_response('registration.html',{"form":regform})


def show_profile(request):
    if 'username' in request.session:
         obj_user=User.objects.all().order_by('-id')
         return render_to_response("index.html",{"obj_user":obj_user,"message":"Hello World"})
    else:
        return HttpResponseRedirect('/login/')

Andreas Kuhne

unread,
Mar 24, 2015, 8:43:47 AM3/24/15
to django...@googlegroups.com
Hi, 

Check out the easy_thumbnails plugin. http://easy-thumbnails.readthedocs.org/en/2.1/

It automatically resizes all images to the size you want if you use it correctly.

Regards,

Andréas

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5938a0d0-af8a-44aa-96c4-5d234f3e2cc4%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Akash Patni

unread,
Mar 24, 2015, 9:04:44 AM3/24/15
to django...@googlegroups.com
can you please suggest me another answer...

--
You received this message because you are subscribed to a topic in the Google Groups "Django users" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/django-users/XjuyFyKNnEI/unsubscribe.
To unsubscribe from this group and all its topics, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.

For more options, visit https://groups.google.com/d/optout.



--
Best Regards,
Akash Patni
Software Engineer

ranosys
  facebooktwitterlinkedingoogleplus 

Head Office: 
Oxley Bizhub, #06-48 | 73 Ubi Road 1 | Singapore - 408733
Tel: +65 66331556  |  HP: +65 98573420

Global Offices:
San Francisco, USA | Jaipur, India | Bikaner, India


Andreas Kuhne

unread,
Mar 24, 2015, 9:12:07 AM3/24/15
to django...@googlegroups.com
You can use Pillow to change the size of the images yourself. That is however pretty complicated and IMO not really worth the effort. I would go with easy_thumbnails.

Regards,

Andréas

Akash Patni

unread,
Mar 25, 2015, 3:27:13 AM3/25/15
to django...@googlegroups.com
For image resizing i have used the following function(in bold).Is it right??

def edit_profile(request):  

    if 'username' in request.session:
        #user_id=request.POST.get('id')
        user_id=request.GET.get('id')
        usr_obj=User.objects.get(id=int(user_id))
        if request.method=="POST":
                if(request.POST['houseno']!=''):
                          houseno=request.POST['houseno']
                else:
                          houseno=None
                if(request.POST['address1']!=''):
                          address1=request.POST['address1']
                else:
                          address1=None
                if(request.POST['city']!=''):
                          city=request.POST['city']
                else:
                          city=None
                if(request.POST['state']!=''):
                          state=request.POST['state']
                else:
                          state=None
                if(request.POST['pincode']!=''):
                          pincode=request.POST['pincode']
                else:
                          pincode=None
                if(request.POST['country']!=''):
                          country=request.POST['country']
                else:
                          country=None
                if(request.POST['comment']!=''):
                          comment=request.POST['comment']
                else:
                          comment=None 
                regform=Edit_Registration(instance=usr_obj,data=request.POST)
                
                if regform.is_valid():
                    try:
                        from PIL import Image, ImageOps
                    except ImportError:
                        import Image
                        import ImageOps
                    imagecontent=request.FILES['image']---At this point it is giving MultiValueDicitionayKeyError(though the field name is same that is image)
                    if imagecontent.mode not in ("L", "RGB"):
                        image = imagecontent.convert("RGB")
                        imageresize = image.resize((100,100), Image.ANTIALIAS) 
                        imageresize.save( 'JPEG', quality=75)
                        regform.save();
                        return HttpResponseRedirect('/index/')
                else:
                    return render_to_response("edit_profile.html",{"form":regform,})
        else:       
           
    
            regform=Edit_Registration(instance=usr_obj)
            return render_to_response("edit_profile.html",{"form":regform,"user_id":user_id})
    else:
        return HttpResponseRedirect('/login/') 

Please Suggest..........


For more options, visit https://groups.google.com/d/optout.

Andreas Kuhne

unread,
Mar 25, 2015, 4:00:12 AM3/25/15
to django...@googlegroups.com
Hi,

Again, you should really put this in your database model instead of in the view. If you use your overriden save function, you would be able to add this there. Also, you check if the image is not an L or RGB image (don't know what L is) and resize it ONLY if it is on of them.

Regards,

Andréas

Akash Patni

unread,
Mar 26, 2015, 12:08:29 AM3/26/15
to django...@googlegroups.com
if regform.is_valid():

                    image_file = StringIO.StringIO(request.FILES['image'].read())
                    image = Image.open(image_file)

                    imageresize = image.resize((100,100), Image.ANTIALIAS) 
                    imageresize.save( 'abc.JPEG', quality=75)
                    regform.save();
                    return HttpResponseRedirect('/index/')
                else:
                    regform=Edit_Registration(instance=usr_obj)
                    return render_to_response("edit_profile.html",{"form":regform,})
        else:       
            #user_id=request.GET.get('id')
            #usr_obj=User.objects.get(id=int(user_id))
     #temp_data={'first_name':user_id.first_name,'last_name':user_id.last_name,'email':user_id.email,'password':user_id.password,'dob':user_id.dob,'mobileno':user_id.mobileno,'houseno':user_id.houseno,'address1':user_id.address1,'city':user_id.city,'state':user_id.state,'pincode':user_id.pincode,'country':user_id.country,'comment':user_id.comment,'sex':user_id.sex}
            regform=Edit_Registration(instance=usr_obj)
            return render_to_response("edit_profile.html",{"form":regform,"user_id":user_id})
    else:
        return HttpResponseRedirect('/login/') 

Hey ,
I am using the above method and able to resize the image but it is only taking JPEG format and i want other format also. Can u please suggest
imageresize.save( 'abc.JPEG', quality=75) it can take three parameters..name, format and quality


For more options, visit https://groups.google.com/d/optout.

Akash Patni

unread,
Mar 26, 2015, 5:42:18 AM3/26/15
to django...@googlegroups.com
Hi,
Resizing is now working properly but the issue is that it is giving key error.
it is taking all files for eg(images.bmp,xx.jpeg) but is giving error when i am tryint to upload the file  (luzern-bridge-8q4_small.jpg) In short it is giving error for jpg format. Please suggest


def edit_profile(request):  
#     data = Thumbnail.objects.get(pk=id)    
    if 'username' in request.session:
        #user_id=request.POST.get('id')
        user_id=request.GET.get('id')
        usr_obj=User.objects.get(id=int(user_id))
        if request.method=="POST":

                regform=Edit_Registration(instance=usr_obj,data=request.POST)
                
                if regform.is_valid():
                     image_file = StringIO.StringIO(request.FILES['image'].read())

                     imagename=request.FILES['image'].name

                     ext = imagename.split('.')[-1]
                     
                     image = Image.open(image_file)

                     imageresize = image.resize((100,100), Image.ANTIALIAS) 

                     filename = hashlib.md5(image_file.getvalue()).hexdigest()+'.'+ext

                     imageresize.save("/home/ranosys-akash/workspace/mysite/src/media/"+filename, ext, quality=75)
                     error at above line(key error...u'JPG')

                     usr_obj.image=filename

                     regform.save();
                     return HttpResponseRedirect('/index/')
                else:
                     regform=Edit_Registration(instance=usr_obj)
                     return render_to_response("edit_profile.html",{"form":regform,})
        else:       
            #user_id=request.GET.get('id')
            #usr_obj=User.objects.get(id=int(user_id))
     #temp_data={'first_name':user_id.first_name,'last_name':user_id.last_name,'email':user_id.email,'password':user_id.password,'dob':user_id.dob,'mobileno':user_id.mobileno,'houseno':user_id.houseno,'address1':user_id.address1,'city':user_id.city,'state':user_id.state,'pincode':user_id.pincode,'country':user_id.country,'comment':user_id.comment,'sex':user_id.sex}
            regform=Edit_Registration(instance=usr_obj)
            return render_to_response("edit_profile.html",{"form":regform,"user_id":user_id})
    else:
        return HttpResponseRedirect('/login/') 
Reply all
Reply to author
Forward
0 new messages