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.

import { openDefaultEditor, createDefaultImageWriter } from './doka.js';

// Open the default image editor in a modal
const editor = openDefaultEditor({
    src: './my-image.jpeg',

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

// Show resulting image preview
editor.on('process', ({ dest }) => {
    const preview = new Image();
    preview.src = URL.createObjectURL(dest);
    document.body.appendChild(preview);
});

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'.

import { openDefaultEditor, createDefaultImageWriter } from './doka.js';

// Open the default image editor in a modal
const editor = openDefaultEditor({
    src: './my-image.jpeg',

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

// Show resulting image preview
editor.on('process', ({ dest }) => {
    const preview = new Image();
    preview.src = URL.createObjectURL(dest);
    document.body.appendChild(preview);
});