import { Area } from 'react-easy-crop/types' ; import { rotateSize , getRadianAngle } from '../../../../src/helpers' ; export const createImage = ( url ) : Promise < HTMLImageElement > => new Promise ( ( resolve , reject ) => { const image = new Image ( ) ; image . addEventListener ( 'load' , ( ) => resolve ( image ) ) ; image . addEventListener ( 'error' , ( error ) => reject ( error ) ) ; image . setAttribute ( 'crossOrigin' , 'anonymous' ) ; image . src = url ; } ) ; /**
 * This function was adapted from the one in the ReadMe of https://github.com/DominicTobias/react-image-crop
 */ export default async function getCroppedImg ( imageSrc , pixelCrop , rotation = 0 , flip = { horizontal : false , vertical : false } ) { const image = await createImage ( imageSrc ) ; const canvas = document . createElement ( 'canvas' ) ; const ctx = canvas . getContext ( '2d' ) ; if ( ! ctx ) { return null ; } const rotRad = getRadianAngle ( rotation ) ; const { width : bBoxWidth , height : bBoxHeight } = rotateSize ( image . width , image . height , rotation ) ; canvas . width = bBoxWidth ; canvas . height = bBoxHeight ; ctx . translate ( bBoxWidth / 2 , bBoxHeight / 2 ) ; ctx . rotate ( rotRad ) ; ctx . scale ( flip . horizontal ? - 1 : 1 , flip . vertical ? - 1 : 1 ) ; ctx . translate ( - image . width / 2 , - image . height / 2 ) ; ctx . drawImage ( image , 0 , 0 ) ; const data = ctx . getImageData ( pixelCrop . x , pixelCrop . y , pixelCrop . width , pixelCrop . height ) ; canvas . width = pixelCrop . width ; canvas . height = pixelCrop . height ; ctx . putImageData ( data , 0 , 0 ) ; return new Promise ( ( resolve , reject ) => { canvas . toBlob ( ( file ) => { resolve ( URL . createObjectURL ( file ) ) ; } , 'image/jpeg' ) ; } ) ; }