import { MimeType , ImageProperties } from '../layer/const' ; export async function drawBlobOnCanvas ( ctx , blob , x = 0 , y = 0 ) { const objectURL = URL . createObjectURL ( blob ) ; try { const imgDrawn = await new Promise ( ( resolve , reject ) => { const img = new Image ( ) ; img . onload = ( ) => resolve ( img ) ; img . onerror = reject ; img . src = objectURL ; } ) ; ctx . drawImage ( imgDrawn , x , y ) ; } finally { URL . revokeObjectURL ( objectURL ) ; } } export async function canvasToBlob ( canvas , mimeFormat ) { return await new Promise ( resolve => canvas . toBlob ( resolve , mimeFormat ) ) ; } export async function getImageProperties ( originalBlob ) { let imgObjectUrl ; const imgCanvas = document . createElement ( 'canvas' ) ; try { const imgCtx = imgCanvas . getContext ( '2d' ) ; imgObjectUrl = URL . createObjectURL ( originalBlob ) ; const img = await new Promise ( ( resolve , reject ) => { const img = new Image ( ) ; img . onload = ( ) => resolve ( img ) ; img . onerror = reject ; img . src = imgObjectUrl ; } ) ; imgCanvas . width = img . width ; imgCanvas . height = img . height ; imgCtx . drawImage ( img , 0 , 0 ) ; const imgData = imgCtx . getImageData ( 0 , 0 , img . width , img . height ) . data ; const stringToMimeType = ( str ) : MimeType => str ; const format = stringToMimeType ( originalBlob . type ) ; return { rgba : imgData , width : img . width , height : img . height , format : format } ; } catch ( e ) { console . error ( e ) ; throw new Error ( e ) ; } finally { imgCanvas . remove ( ) ; if ( imgObjectUrl ) { URL . revokeObjectURL ( imgObjectUrl ) ; } } } export async function getBlob ( imageProperties ) { const { rgba , width , height , format } = imageProperties ; const imgCanvas = document . createElement ( 'canvas' ) ; try { imgCanvas . width = width ; imgCanvas . height = height ; const imgCtx = imgCanvas . getContext ( '2d' ) ; const newImg = new ImageData ( rgba , width , height ) ; imgCtx . putImageData ( newImg , 0 , 0 ) ; const blob = await canvasToBlob ( imgCanvas , format ) ; return blob ; } catch ( e ) { console . error ( e ) ; throw new Error ( e ) ; } finally { imgCanvas . remove ( ) ; } } export async function validateCanvasDimensions ( canvas ) { const blob = await new Promise ( resolve => canvas . toBlob ( resolve ) ) ; if ( blob === null ) { return false ; } return true ; }