v8.38.0

Resize an image

We can use the targetSize property on the createDefaultImageWriter function to automatically resize images to fit a target width and height.

This example is a bout automatic resizing of the output image, to let the user resize the image in the editor we need to enable the resize plugin.

<!DOCTYPE html>

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

<img src="" alt="" />

<style>
    .pintura-editor {
        height: 600px;
    }
</style>

<div id="editor"></div>

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

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',

        // This will scale down the image to fit in a 256 × 256 square
        imageWriter: {
            targetSize: {
                width: 256,
                height: 256,
            },
        },
    });

    editor.on('process', (imageState) => {
        document.querySelector('img').src = URL.createObjectURL(
            imageState.dest
        );
    });
</script>

By setting the fit and upscale properties we can further control how the editor scales images. By setting upscale to true images smaller than 256 × 256 will be upscaled to fit the bounds.

If the image isn't a square it won't fill the square bounding box, the image will be scaled up until one of the edges is 256 pixels in length. To always cover the square target size we can set fit to 'cover'.

<!DOCTYPE html>

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

<img src="" alt="" />

<style>
    .pintura-editor {
        height: 600px;
    }
</style>

<div id="editor"></div>

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

    const editor = appendDefaultEditor('#editor', {
        src: 'image.jpeg',

        // This will scale down the image to fit in a 256 × 256 square
        imageWriter: {
            targetSize: {
                width: 256,
                height: 256,
                upscale: true,
                fit: 'cover',
            },
        },
    });

    editor.on('process', (imageState) => {
        document.querySelector('img').src = URL.createObjectURL(
            imageState.dest
        );
    });
</script>