Using react-cropper to crop my image. Before cropping image file size was 2mb, after 6mb

101 views Asked by At
const getCropData2 = () => {
        if (typeof cropperRef2.current?.cropper !== 'undefined') {
            const cropper = cropperRef2.current?.cropper;
            if ((cropper.getCroppedCanvas().toDataURL().length * (3/4)) / 1024 < 2048) FitnessStore.editFitnessImagesUpload({image: cropper.getCroppedCanvas().toDataURL()});
            else {
                FitnessStore.editFitnessImagesUpload({image: null});
                alert('Размер файла превышает 2 мб');
            }
            setImage2(true);
            handleClose2();
        }
    };
<Dialog
                open={open2}
                onClose={handleClose2}
                aria-labelledby="alert-dialog-title"
                aria-describedby="alert-dialog-description"
            >
                <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        {!image2 && FitnessStore.fitnessImagesUpload.image ? <>
                            <Cropper
                                aspectRatio={10 / 11}
                                style={{height: 400}}
                                preview=".img-preview"
                                guides={true}
                                src={FitnessStore.fitnessImagesUpload.image}
                                ref={cropperRef2}
                                dragMode={'move'}
                                background={false}
                                responsive={true}
                                autoCropArea={1}
                                checkOrientation={false}
                                viewMode={1}
                                minCropBoxHeight={10}
                                minCropBoxWidth={10}
                            />
                        </> : null}
                    </DialogContentText>
                </DialogContent>
                <DialogActions>
                    <Button onClick={getCropData2}>Обрезать</Button>
                </DialogActions>
            </Dialog>

Here is my Cropper component and ref to control proccess after cropping. After the posting my image to cropper in some cases images get larger than it was before copping. How to fix it? I need a file less than 2mb

1

There are 1 answers

0
Olga Khmaruk On
cropperRef.current?.cropper
 .getCroppedCanvas()
 .toDataURL("image/jpeg") 

This piece of code was helpful for me. Try to specify the mime type.