sekoyo / react-image-crop

A responsive image cropping tool for React
ISC License
3.83k stars 342 forks source link

Need to update function to get cropped image if size of image doesn't match size of cropper component #380

Open MR-Neto opened 4 years ago

MR-Neto commented 4 years ago

I had to change the function to get the cropped image because the size of image cropper component was not the same as the original image.

export function getCroppedImg(originalImage, sizeImageCropper, crop, fileName) {
    const canvas = document.createElement('canvas');
    const scaleX = originalImage.naturalWidth / sizeImageCropper.width;
    const scaleY = originalImage.naturalHeight / sizeImageCropper.height;
    canvas.width = crop.width;
    canvas.height = crop.height;
    const ctx = canvas.getContext('2d');

    ctx.drawImage(
        originalImage,
        crop.x * scaleX,
        crop.y * scaleY,
        crop.width * scaleX,
        crop.height * scaleY,
        0,
        0,
        crop.width,
        crop.height,
    );

    return new Promise(resolve => {
        canvas.toBlob(
            blob => {
                blob.name = fileName;
                resolve(blob);
            },
            'image/jpeg',
            1,
        );
    });
}

Then I call the function:

        const blob = await getCroppedImg(
            imageInicial,
            document.querySelector('img[class="ReactCrop__image"]'),
            crop,
            'cropped',
        );
sekoyo commented 3 years ago

Hi, the image crop is intentionally the size of the crop they are drawing. I assume this is using an offscreen image at the original size and cropping from that? Requires more setup that I can show in a simple example, think it will work better as a codesanbox demo.