Exemplo n.º 1
0
def add(request):
    
    print "Adding project"
    
    form = ImageUploadForm(request.POST, request.FILES)
    
    print form
    
    if form.is_valid():
        
        print "Form valid"
        
        p = Project()
        p.owner = request.user
        p.name = form.cleaned_data['name']
        p.architect = form.cleaned_data['architect']        
        
        try:
            p.address = form.cleaned_data['address']
            p.latitude = form.cleaned_data['latitude']
            p.longitude = form.cleaned_data['longitude']
        except KeyError:
            pass
        
        p.pub_date = timezone.now()
        p.image_file = form.cleaned_data['image']
        
        print form.cleaned_data
        
        p.save()
        
        image_file = request.FILES['image']
        
        image_str = ''
        for c in image_file.chunks():
            image_str += c
        image_file_strio = StringIO(image_str)
        image = PImage.open(image_file_strio)
        if image.mode != "RGB":
            image = image.convert('RGB')

        rotation_code = get_rotation_code(image)
        image = rotate_image(image, rotation_code)    
        
        width, height = image.size
        
        wh_ratio = float(width) / float(height)
                
        if width <= 400 and height <= 300:
            cropped_image = image
        else:
            if wh_ratio > 4.0/3.0:
                if height > 300:
                    ratio = 300.0 / float(height)
                    image.thumbnail((int(ceil(width * ratio)), 300), PImage.ANTIALIAS)
                    width, height = image.size
            else:
                if width > 400:
                    ratio = 400.0 / float(width)
                    image.thumbnail((400, int(ceil(height * ratio))), PImage.ANTIALIAS)
                    width, height = image.size
                    
            left = max(int(width/2)-200, 0)
            bottom = max(int(height/2)-150, 0)
            right = min(int(width/2)+200, width)
            top = min(int(height/2)+150, height)
            
            
            cropped_image = image.crop([max(int(width/2)-200, 0), max(int(height/2)-150, 0), min(int(width/2)+200, width), min(int(height/2)+150, height)])
                
                            
        
        
        filename, ext = os.path.splitext(p.image_file.name)
        thumb_filename = settings.MEDIA_ROOT + filename + "-thumb" + ext
        #cropped_image.save(thumb_filename, "JPEG")
        
        f = StringIO()
        try:
            cropped_image.save(f, format='jpeg')
            s = f.getvalue()
            print type(p.thumbnail_file)
            p.thumbnail_file.save(thumb_filename, ContentFile(s))
            p.save()
        finally:
            f.close()    
            
        print "Project added"
        
        return HttpResponse(p.id)
    
    
    return HttpResponse('')