Fork me on GitHub

Image

Image widget.

Provide a form action handler storing images somewhere. File system is used in this example.

runtime_images_dir = os.path.join(os.path.dirname(__file__), 'images_tmp')

def save_image(widget, data):
    name = 'yafowil.widget.image.image'
    image = data.extracted[name]['image']
    image_path = os.path.join(runtime_images_dir, name + '.jpg')
    if image['action'] == 'keep':
        return
    if image['action'] == 'delete':
        os.remove(image_path)
        return
    # read from scales, see below
    image['scales']['default'].save(image_path, 'jpeg', quality=100)

The images should be available for the browser by URL in order to make image blueprint work as expected.

Create widget.

name = 'yafowil.widget.image.image'
image_name = name + '.jpg'
image_path = os.path.join(runtime_images_dir, image_name)
image_value = UNSET
if os.path.exists(image_path):
    image_data = read_image(name)
    image_value = {
        'file': StringIO(image_data),
        'mimetype': 'image/jpg',
    }
form = factory('fieldset', name=name)
form['image'] = factory('#field:image', value=image_value, props={
    'label': 'Image',
    'required': 'No Image uploaded',
    'maxsize': (1024, 768),
    'scales': {'default': (400, 400)},
    'src': image_name,
    'error.class': 'help-block',
})