Exemple #1
0
def upload_image(request):
    filename = request.POST['file'].filename
    input_file = request.POST['file'].file
    obj_id = request.matchdict['id']
    obj_type = request.matchdict['type']

    path_to_images = os.path.join(os.path.dirname(nextgisbio.__file__),
                                  'static/data/images')
    date_now = datetime.datetime.now().strftime('%Y-%m-%d')
    path_to_images_now = os.path.join(path_to_images, date_now)

    if not os.path.exists(path_to_images_now):
        os.mkdir(path_to_images_now)

    # from http://stackoverflow.com/questions/2782229/most-lightweight-way-to-create-a-random-string-and-a-random-hexadecimal-number
    random_file_name = str(uuid.uuid4())
    base_file_path = os.path.join(path_to_images_now,
                                  '.'.join([random_file_name, 'jpg']))

    with open(base_file_path, 'wb') as output_file:
        shutil.copyfileobj(input_file, output_file)

    for key_size in THUMBNAIL_SIZES:
        try:
            im = Image.open(base_file_path)
            im.thumbnail(THUMBNAIL_SIZES[key_size], Image.BICUBIC)
            im.save(os.path.join(
                path_to_images_now,
                '.'.join([random_file_name + '_' + key_size, 'jpg'])),
                    'JPEG',
                    quality=70)
        except IOError:
            print "cannot create thumbnail for '%s'" % base_file_path

    with transaction.manager:
        dbSession = DBSession()
        image = Images()
        image.name = filename
        image.url = '/static/data/images/%s/%s.jpg' % (date_now,
                                                       random_file_name)
        image.size = os.path.getsize(base_file_path)
        image.local = base_file_path
        dbSession.add(image)

        if obj_type == 'card':
            card_image = CardsImages()
            card_image.image = image
            card_image.card = dbSession.query(Cards).filter_by(id=obj_id).one()
            dbSession.add(card_image)

        photo_json = image.as_json_dict()

    return photo_json