예제 #1
0
def saveImage(request):
    """
    Image drag and drop, saves the files and to the database.
    """
    if request.method == 'POST':
        timeMark = time.time()
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            uploadedFile = request.FILES['file']
            print "Uploaded file = " + str(uploadedFile)
            print "request = " + str(request)
            # If this image has exif data in it, extract it

            exifData, exifTimeString = getExifTimeString(request, uploadedFile)

            form_tz = form.getTimezone()
            exifTime = getExifTime(request, exifTimeString, uploadedFile,
                                   form_tz)

            author = computeAuthor(request)
            vehicle = form.getVehicle()
            camera = getCameraByExif(exifData)

            # create a new image set instance
            newImageSet = create_image_set(file=uploadedFile,
                                           filename=uploadedFile.name,
                                           author=author,
                                           vehicle=vehicle,
                                           camera=camera,
                                           form_tz=form_tz,
                                           form_tz_name=form.getTimezoneName(),
                                           exif_data=exifData,
                                           exif_time=exifTime,
                                           object_id=request.POST.get(
                                               'object_id', None),
                                           time_mark=timeMark)

            newImageSet.finish_initialization(request)
            relayIfNeeded(request, newImageSet)

            # pass the image set to the client as json.
            return JsonResponse(
                {
                    'success': 'true',
                    'json': newImageSet.toMapDict()
                },
                encoder=DatetimeJsonEncoder,
                safe=False)
        else:
            return JsonResponse(
                {
                    'error': 'Imported image is not valid',
                    'details': form.errors
                },
                status=406)
예제 #2
0
파일: views.py 프로젝트: xgds/xgds_image
def saveImage(request):
    """
    Image drag and drop, saves the files and to the database.
    """
    if request.method == "POST":
        timeMark = time.time()
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # create and save a single image obj
            uploadedFile = request.FILES["file"]
            newImage = SINGLE_IMAGE_MODEL.get()(file=uploadedFile)

            form_tz = form.getTimezone()
            resource = form.getResource()
            exifData = getExifData(newImage)

            # save image dimensions and file size
            try:
                newImage.width = int(getExifValue(exifData, "ExifImageWidth"))
                newImage.height = int(getExifValue(exifData, "ExifImageHeight"))
            except:
                pass

            newImage.fileSizeBytes = uploadedFile.size

            # get exif time
            exifTime = None
            exifTimeString = getExifValue(exifData, "DateTimeOriginal")
            if not exifTimeString:
                exifTimeString = getExifValue(exifData, "DateTime")

            if exifTimeString:
                exifTime = datetime.strptime(str(exifTimeString), "%Y:%m:%d %H:%M:%S")
                if (form_tz != pytz.utc) and exifTime:
                    localized_time = form_tz.localize(exifTime)
                    exifTime = TimeUtil.timeZoneToUtc(localized_time)
                else:
                    exifTime = exifTime.replace(tzinfo=pytz.utc)
            else:
                # read the time from the last modified time that we pushed in from imageUpload.js
                if "HTTP_LASTMOD" in request.META:
                    modtimesString = request.META["HTTP_LASTMOD"]
                    if modtimesString:
                        modtime = None
                        theImages = modtimesString.split(",")
                        for i in theImages:
                            k, v = i.split("||")
                            if k == str(uploadedFile.name):
                                modtime = datetime.fromtimestamp(int(v) / 1000)
                                break
                        if modtime:
                            localized_time = form_tz.localize(modtime)
                            exifTime = TimeUtil.timeZoneToUtc(localized_time)
            if not exifTime:
                exifTime = datetime.now(pytz.utc)
            # create a new image set instance

            author = None
            if request.user.is_authenticated():
                author = request.user  # set user as image author
            elif "username" in request.POST:
                try:
                    username = str(request.POST["username"])
                    author = User.objects.get(username=username)
                except:
                    author = User.objects.get(username="******")

            newImageSet = IMAGE_SET_MODEL.get()()
            newImageSet.acquisition_time = exifTime
            newImageSet.acquisition_timezone = form.getTimezoneName()
            fileName = uploadedFile.name
            newImageSet.name = fileName
            newImageSet.camera = getCameraObject(exifData)

            newImageSet.track_position = getTrackPosition(exifTime, resource)
            newImageSet.exif_position = buildExifPosition(exifData, newImageSet.camera, resource, exifTime, form_tz)

            newImageSet.author = author
            newImageSet.resource = resource
            newImageSet.finish_initialization(request)

            nowTime = time.time()
            uploadAndSaveTime = nowTime - timeMark
            newImageSet.uploadAndSaveTime = uploadAndSaveTime
            overallStartTime = cache.get("imageAutoloadGlobalTimeMark", None)
            if overallStartTime:
                totalTimeSinceNotify = nowTime - float(overallStartTime)
                newImageSet.totalTimeSinceNotify = totalTimeSinceNotify
            newImageSet.save()

            # link the "image set" to "image".
            newImage.imageSet = newImageSet
            newImage.save()

            # create a thumbnail
            thumbnailStream = createThumbnailFile(newImage.file)
            SINGLE_IMAGE_MODEL.get().objects.create(
                file=thumbnailStream, raw=False, thumbnail=True, imageSet=newImageSet
            )

            # create deep zoom tiles for viewing in openseadragon.
            if newImageSet.create_deepzoom:
                deepzoomTilingThread = Thread(target=newImageSet.create_deepzoom_image)
                deepzoomTilingThread.start()
            #                newImageSet.create_deepzoom_image()

            imageSetDict = newImageSet.toMapDict()
            # pass the image set to the client as json.
            return HttpResponse(
                json.dumps({"success": "true", "json": imageSetDict}, cls=DatetimeJsonEncoder),
                content_type="application/json",
            )
        else:
            return HttpResponse(
                json.dumps({"error": "Imported image is not valid", "details": form.errors}),
                content_type="application/json",
            )
예제 #3
0
def saveImage(request):
    """
    Image drag and drop, saves the files and to the database.
    """
    if request.method == 'POST':
        timeMark = time.time()
        form = UploadFileForm(request.POST, request.FILES)
        if form.is_valid():
            # create and save a single image obj
            uploadedFile = request.FILES['file']
            newSingleImage = SINGLE_IMAGE_MODEL.get()(file=uploadedFile)

            form_tz = form.getTimezone()
            resource = form.getResource()
            exifData = getExifData(newSingleImage)

            # save image dimensions and file size
            try:
                newSingleImage.width = int(
                    getExifValue(exifData, 'ExifImageWidth'))
                newSingleImage.height = int(
                    getExifValue(exifData, 'ExifImageHeight'))
            except:
                pass

            newSingleImage.fileSizeBytes = uploadedFile.size

            # get exif time
            exifTime = None
            exifTimeString = getExifValue(exifData, 'DateTimeOriginal')
            if not exifTimeString:
                exifTimeString = getExifValue(exifData, 'DateTime')

            if exifTimeString:
                exifTime = datetime.strptime(str(exifTimeString),
                                             '%Y:%m:%d %H:%M:%S')
                if (form_tz != pytz.utc) and exifTime:
                    localized_time = form_tz.localize(exifTime)
                    exifTime = TimeUtil.timeZoneToUtc(localized_time)
                else:
                    exifTime = exifTime.replace(tzinfo=pytz.utc)
            else:
                # read the time from the last modified time that we pushed in from imageUpload.js
                if 'HTTP_LASTMOD' in request.META:
                    modtimesString = request.META['HTTP_LASTMOD']
                    if modtimesString:
                        modtime = None
                        theImages = modtimesString.split(',')
                        for i in theImages:
                            k, v = i.split('||')
                            if k == str(uploadedFile.name):
                                modtime = datetime.fromtimestamp(int(v) / 1000)
                                break
                        if modtime:
                            localized_time = form_tz.localize(modtime)
                            exifTime = TimeUtil.timeZoneToUtc(localized_time)
            if not exifTime:
                exifTime = datetime.now(pytz.utc)
            # create a new image set instance

            author = None
            if request.user.is_authenticated():
                author = request.user  # set user as image author
            elif 'username' in request.POST:
                try:
                    username = str(request.POST['username'])
                    author = User.objects.get(username=username)
                except:
                    author = User.objects.get(username='******')

            if 'object_id' in request.POST:
                newImageSet = IMAGE_SET_MODEL.get()(
                    pk=int(request.POST['object_id']))
            else:
                newImageSet = IMAGE_SET_MODEL.get()()

            newImageSet.acquisition_time = exifTime
            newImageSet.acquisition_timezone = form.getTimezoneName()
            fileName = uploadedFile.name
            newImageSet.name = fileName
            newImageSet.camera = getCameraObject(exifData)

            newImageSet.track_position = getTrackPosition(exifTime, resource)
            newImageSet.exif_position = buildExifPosition(
                exifData, newImageSet.camera, resource, exifTime, form_tz)

            newImageSet.author = author
            newImageSet.resource = resource
            newImageSet.finish_initialization(request)

            nowTime = time.time()
            uploadAndSaveTime = nowTime - timeMark
            newImageSet.uploadAndSaveTime = uploadAndSaveTime
            overallStartTime = cache.get("imageAutoloadGlobalTimeMark", None)
            if overallStartTime:
                totalTimeSinceNotify = nowTime - float(overallStartTime)
                newImageSet.totalTimeSinceNotify = totalTimeSinceNotify
            newImageSet.save()

            # link the "image set" to "image".
            newSingleImage.imageSet = newImageSet
            newSingleImage.save()

            # relay if needed
            if 'relay' in request.POST:
                # create the record for the datum
                # fire a message for new data
                deletePostKey(request.POST, 'relay')
                addRelay(newImageSet, request.FILES, json.dumps(request.POST),
                         reverse('xgds_save_image'))
            # create a thumbnail
            thumbnailStream = createThumbnailFile(newSingleImage.file)
            SINGLE_IMAGE_MODEL.get().objects.create(file=thumbnailStream,
                                                    raw=False,
                                                    thumbnail=True,
                                                    imageSet=newImageSet)

            # create deep zoom tiles for viewing in openseadragon.
            if (newImageSet.create_deepzoom):
                deepzoomTilingThread = Thread(
                    target=newImageSet.create_deepzoom_image)
                deepzoomTilingThread.start()


#                newImageSet.create_deepzoom_image()

            imageSetDict = newImageSet.toMapDict()
            # pass the image set to the client as json.
            return HttpResponse(json.dumps(
                {
                    'success': 'true',
                    'json': imageSetDict
                },
                cls=DatetimeJsonEncoder),
                                content_type='application/json')
        else:
            return HttpResponse(json.dumps({
                'error': 'Imported image is not valid',
                'details': form.errors
            }),
                                content_type='application/json')