Editing a file in a file input element

The most straightforward method to offer image editing in a form. We pass the contents of the file input to the openDefaultEditor factory which opens the file in Pintura and returns a new file after editing is complete.

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

<script type="module">
    // only need this factory method to open the editor
    import { openDefaultEditor } from './pintura.js';

    // get a reference to our file input element
    const fileInput = document.querySelector('input[type="file"]');

    // wait for the change event to fire
    fileInput.addEventListener('change', () => {
        // no files selected
        if (!fileInput.files.length) return;

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

        // store the resulting file in the file input
        editor.on('process', ({ dest }) => {
            // create a files list
            const dataTransfer = new DataTransfer();
            dataTransfer.items.add(dest);

            // update the file input
            fileInput.files = dataTransfer.files;
        });
    });
</script>