示例#1
0
def upload_pic(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            image = ImageModel(image=request.FILES['image'])
            image.save()
            return render(request, 'success.html')
    else:
        form = ImageUploadForm()
    return render(request, 'upload.html', {'form': form})
示例#2
0
def image_upload(request):
    user = request.user
    if request.method != 'POST':
        return HttpResponse(status=404)
    else:
        form = ImageUploadForm(request.POST, request.FILES)
        form.author = user
        if form.is_valid():
            iu = form.save()
            item_id = request.GET.get('item_id', None)
            if item_id:
                item = Item.objects.get(id=int(item_id))
                iu.content_object = item
                iu.save()
            f = request.FILES.get('image')
            files = [{
                'url': iu.image.url,
                'name': unicode(iu.uuid),
                "type": "image/png",
                'thumbnailUrl': iu.image.url,
                'size': f.size,
                'deleteUrl': '/image_delete/' + unicode(iu.uuid) + '/',
                'deleteType': "DELETE",
            }]
            data = {"files": files}
            response = JSONResponse(data, {}, response_mimetype(request))
            response['Content-Disposition'] = 'inline; filename=files.json'
            return response
示例#3
0
文件: views.py 项目: longnight/ajax
def img_upload(request):
    if request.method == 'POST':
        img_form = ImageUploadForm(request.POST, request.FILES)
        if img_form.is_valid():
            img_path = ImagsPath(img=img_form.cleaned_data.get('img'))
            img_path.save()
            # location = img_path.img.url
            location = 'http://' + request.get_host() + img_path.img.url
            # rv = {'location': location}
            # print rv
            status = 200
            print location
            # import pdb;pdb.set_trace()
            script_string = """
            <script>top.$('.mce-btn.mce-open').parent().find('.mce-textbox').val('%s').closest('.mce-window').find('.mce-primary').click();</script>
            """ % location
            sleep(3)
            return HttpResponse(script_string, status=status)
        else:
            rv = img_form.errors
            print rv
            status = 409
            return HttpResponse("<script>alert('%s');</script>" %
                                img_form.errors,
                                status=status)
示例#4
0
文件: views.py 项目: longnight/ajax
def comments(request):

    form = CommentForm(request.POST or None)

    img_form = ImageUploadForm()
    if request.method == "POST" and form.is_valid():
        comment = Comment(content=form.cleaned_data.get('content'))
        if form.cleaned_data.get('quote_id'):
            comment.quote_id = form.cleaned_data.get('quote_id')

        if request.is_ajax():
            print 'ajax coming~~!'
            print comment.id
            print comment.content
            comment.content += ' (from ajax!)'

        comment.save()
        print 'success!'
        return redirect('/comments/')

    comments = Comment.objects.order_by('-id').all()[:8]
    img_paths = ImagsPath.objects.order_by('-id').all()[:5]
    c = {
        'comments': comments,
        'form': form,
        'img_form': img_form,
        'img_paths': img_paths,
    }

    return render(request, 'comments.html', c)
示例#5
0
def upload_pic(request):
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        imageName = str(request.FILES['image'])
        print "Hello this is :"+imageName
        # print request.POST
        if form.is_valid():
            m = ExampleModel()
            m.model_pic = form.cleaned_data['image']
            m.save()

            im = imClassify.imClassify()
            imagePath = 'utilities/images/'+imageName
            resultList = im.main(imagePath)
            print  "THi is view ;;;;;; ------ ;;;;"
            print resultList

            # Considering only the first string
            # [['giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca', 0.89233041], ['indri, indris, Indri indri, Indri brevicaudatus', 0.0085870409], ['lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens', 0.0026423461], ['custard apple', 0.0014067066], ['earthstar', 0.0010706335]]
            nameOfTopic = resultList[0][0].split(",")[0]
            print nameOfTopic

            du = duckduckGo.duckduckGo()
            description = du.getInfo(nameOfTopic)

            print description

            # Now deleting the file
            if os.path.isfile(imagePath):
                os.remove(imagePath)

            return render(request,'result.html',{'imageName':nameOfTopic, 'description':description})
    return HttpResponseForbidden('allowed only via POST')
示例#6
0
def user_settings(req):
    if not req.user.is_authenticated() or req.user.is_anonymous():
        return redirect("index")
    tpl = "website/settings.html"
    ctxt = dict()
    ctxt["change_pwd_form"] = PasswordChangeForm(req.user)
    loc = req.user.locutor
    if req.method == "POST":
        random_pic_name = "".join(
            [choice(string.ascii_letters) for i in xrange(32)])
        if 'img' in req.FILES.keys():
            req.FILES['img'].name = random_pic_name
        picform = ImageUploadForm(req.POST, req.FILES)
        if picform.is_valid():
            # TODO delete old file
            #             with open(settings.MEDIA_ROOT + 'pic/' + loc.pic.name, 'wb+') as destination:
            #                 for chunk in loc.pic.chunks():
            #                    destination.write(chunk)
            loc.pic.delete()
            loc.pic = picform.cleaned_data["img"]
            # File(random_pic_name, req.FILES['files[]'])
            loc.save()
            req.user.save()
        else:
            print picform.errors
    return render(req, tpl, ctxt)
示例#7
0
    def post(self, request, *args, **kwargs):
        post = request.POST
        oled_id = post.get('oled_id', '')
        image_form = ImageUploadForm(request.POST, request.FILES or None)
        if image_form.is_valid():
            oled = Oled.objects.get(oled_id=oled_id)
            oled.oledimage_set.create(
                image_image=request.FILES.get('file', ''),
                image_thumbnail=request.FILES.get('file', ''))
            return HttpResponse('Posted')

        print('fail')
        return HttpResponse('Failed')
def upload():
    form = ImageUploadForm()
    if form.validate_on_submit():
        # save file
        safe_filename = secure_filename(form.image_file.data.filename)
        final_filename = f'{current_user.id}_{str(current_user.images_count + 1)}_{safe_filename}'
        upload_set.save(form.image_file.data, name=final_filename)

        # add image row in db
        image = Image()
        image.title = form.title.data
        image.filename = final_filename
        image.user_id = current_user.id
        db.session.add(image)
        db.session.commit()

        # update user uploaded images count
        current_user.images_count += 1

        # detect faces for current image and save data in db
        detector = FaceDetector(final_filename)
        result = detector.get_detections()
        data = result.get('data')
        if data:
            image_id = image.id
            detections_to_commit = []
            for item in data:
                detection = Detection()
                detection.topleft_x = item['x']
                detection.topleft_y = item['y']
                detection.width = item['width']
                detection.height = item['height']
                detection.image_id = image_id
                detections_to_commit.append(detection)

            if detections_to_commit:
                db.session.add_all(detections_to_commit)
                db.session.commit()

        flash(f'File {safe_filename} has been uploaded successfully!', 'success')
        return redirect(url_for('home'))
    return render_template('upload.html', form=form, title='Image upload page')
示例#9
0
def upload_image(request):
    """
    Handles image uploads and assigns them to the correct user. Resizes the image before uploading.

    The uploaded image's URL is in the HTTP header (Location)
    """
    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            img = Image()
            img.user = request.user
            img.note_id = form.cleaned_data['note']
            img.image = form.cleaned_data['image']
            img.save()

            # Build a response
            response = HttpResponse(status=201)
            response['Location'] = img.image.url.replace(
                settings.AWS_MEDIA_URL, settings.MEDIA_URL, 1)
            return response
        else:
            return HttpResponse(status=400)
    return HttpResponseForbidden()
示例#10
0
def upload_pic(request):

    if request.method == 'POST':
        form = ImageUploadForm(request.POST, request.FILES)
        if form.is_valid():
            # os.remove(file) for file in os.listdir('path/to/directory') if file.endswith('.png')
            for file in os.listdir(os.path.join(BASE_DIR, 'media', 'img')):
                if (file.endswith('.jpg')):
                    os.remove(os.path.join(BASE_DIR, 'media', 'img', file))
            for file in os.listdir(os.path.join(BASE_DIR, 'static', 'img')):
                if (file.endswith('.jpg')):
                    os.remove(os.path.join(BASE_DIR, 'static', 'img', file))
            m = ExampleModel()
            m.model_pic = form.cleaned_data['image']
            m.save()
            for file in os.listdir(os.path.join(BASE_DIR, 'media', 'img')):
                if (file.endswith('.jpg')):
                    shutil.move(
                        os.path.join(BASE_DIR, 'media', 'img', file),
                        os.path.join(BASE_DIR, 'media', 'img', 'main.jpg'))
                    shutil.copy(
                        os.path.join(BASE_DIR, 'media', 'img', 'main.jpg'),
                        os.path.join(BASE_DIR, 'static', 'img', 'main.jpg'))
            pathForImage = os.path.join(BASE_DIR, 'static', 'img', 'main.jpg')
            mainImage = cv2.imread(pathForImage)
            p = subprocess.Popen(
                '/usr/local/src/openalpr/src/build/alpr -c kz -p kz -j ' +
                pathForImage,
                stdout=subprocess.PIPE,
                shell=True)
            (output, err) = p.communicate()
            p_status = p.wait()
            main_out = output.split('\n')[0]
            data = (json.loads(main_out))['results']
            # print(data)
            if (len(data) == 0):
                data = {'plateNumber': 'НОМЕР БЫЛ НЕ НАЙДЕН'}
                return render(request, 'second.html', data)
            else:
                coordinates = data[0]['coordinates']
                top_left = coordinates[1]
                bottom_right = coordinates[3]
                y1 = top_left['y']
                x1 = top_left['x']

                y2 = bottom_right['y']
                x2 = bottom_right['x']

                cv2.rectangle(mainImage, (x1, int(y1)), (x2, int(y2)),
                              (0, 255, 0), 1)
                cv2.imwrite(pathForImage, mainImage)
                plates = data[0]['candidates']
                plate_number = (data[0]['candidates'][0]['plate'])

                best_predicted = data[0]['candidates'][0]['plate']
                best_predicted_by_pattern = []
                for plate in plates:
                    if (plate['matches_template'] == 1):
                        best_predicted_by_pattern.append(plate['plate'])
                if (len(best_predicted_by_pattern) != 0):
                    best_predicted = best_predicted_by_pattern[0]
                data = {'plateNumber': best_predicted}
                return render(request, 'second.html', data)
    return HttpResponseForbidden('allowed only via POST')