canvas.toBlob((blob) => {
console.log(blob);
const formData = new FormData();
formData.append('image', blob, 'image.png');
console.log(formData);
}, 'image/png');
import { useCallback, useEffect, useRef, useState, ChangeEvent } from 'react';
import { Crop } from 'react-image-crop';
export const useCropImage = (
width: number,
height: number,
minWidth = 250,
minHeight = 250
) => {
const imgRef = useRef<any>(null);
const [crop, setCrop] = useState<Crop>({
unit: 'px',
x: 130,
y: 36,
width: width < minWidth ? minWidth : width,
height: height < minHeight ? minHeight : height
});
const [image, setImage] = useState<any>();
const [imageSrc, setImageSrc] = useState<any>();
const [nameFile, setNameFile] = useState('');
const onSelectFile = (evt: ChangeEvent<HTMLInputElement>) => {
if (evt.target.files && evt.target.files.length > 0) {
const reader = new FileReader();
reader.readAsDataURL(evt.target.files[0]);
setNameFile(evt.target.files[0].name.replace(' ', ''));
reader.addEventListener('load', () => setImageSrc(reader.result));
}
};
const onLoad = useCallback((evt: any) => setImage(evt.target), []);
const cropImageNow = () => {
if (image) {
const canvas = document.createElement('canvas');
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
const ctx = canvas.getContext('2d');
if (ctx) {
const pixelRatio = window.devicePixelRatio;
canvas.width = crop.width * pixelRatio;
canvas.height = crop.height * pixelRatio;
ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);
}
canvas.toBlob((blob) => {
const form = new FormData();
form.append('photo', blob);
console.log(form);
})
// const base64Image = canvas.toDataURL('image/jpeg');
// return base64Image;
// return dataURLtoFile(base64Image, nameFile);
}
};
return {
crop,
imgRef,
onLoad,
setCrop,
imageSrc,
nameFile,
minWidth,
minHeight,
setImageSrc,
cropImageNow,
onSelectFile
};
};
const canvas = document.createElement("canvas") as HTMLCanvasElement;
const scaleX = image.naturalWidth / image.width;
const scaleY = image.naturalHeight / image.height;
canvas.width = crop.width;
canvas.height = crop.height;
canvas
.getContext("2d")!
.drawImage(
image,
crop.x * scaleX,
crop.y * scaleY,
crop.width * scaleX,
crop.height * scaleY,
0,
0,
crop.width,
crop.height
);