v8.89.6

Editing an image in a file input element

The most straightforward method to offer image editing in a form.

We pass the contents of a file input element to the openDefaultEditor factory which opens the file in Pintura and sets the edited image as the new file input value.

Setting the value of a file input is possible on browsers that support the DataTransfer constructor, currently this is Firefox, Chrome, Chromium powered browsers, and Safari 14.1.

<!DOCTYPE html>

<head>
    <link rel="stylesheet" href="./pintura.css" />
</head>

<input type="file" accept="image/*" id="fileInput" />

<script type="module">
    import { openDefaultEditor } from './pintura.js';

    const fileInput = document.querySelector('#fileInput');

    fileInput.addEventListener('change', () => {
        // Exit if no files selected
        if (!fileInput.files.length) return;

        // Edit the selected file
        const editor = openDefaultEditor({
            imageCropAspectRatio: 1,
            src: fileInput.files[0],
        });

        // When done, assign the resulting file to the file input
        editor.on('process', (imageState) => {
            // Create a files list
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(imageState.dest);

            // Assign new files
            fileInput.files = dataTransfer.files;
        });
    });
</script>