Skip to content

Instantly share code, notes, and snippets.

@Rulsky
Created August 31, 2017 13:22
Show Gist options
  • Save Rulsky/7e1fd42381fb49fc2648bc2e86fba55e to your computer and use it in GitHub Desktop.
Save Rulsky/7e1fd42381fb49fc2648bc2e86fba55e to your computer and use it in GitHub Desktop.
image optimisation via canvas api
/**
* @description promisified optimisation of image via canvas API
*
* @param {File} file - a file of an image which should be transformed
* @param {integer} destHeight - a desired height of an output image Blob|DataURL
* @param {integer} quality - a desired level of compression of an output image Blob|DataURL
* @param {string} mimeType - mimeType of of an output image Blob|DataURL
* @param {string} to - part of canvas conversion method name (can be 'DataURL' or 'Blob' as a `Canvas.toDataURL()` or `Canvas.toBlob()`)
*
* @return {Promise}
*/
function optimiseImage(file, destHeight, mimeType, quality, to) {
return new Promise( (resolve, reject) => {
const reader = new FileReader()
reader.onabort = () => reject('file reading was aborted')
reader.onerror = () => reject('file reading has failed. try once again')
reader.onload = () => {
const result = reader.result,
img = new Image()
img.onload = () => {
const resizeMultiplier = destHeight / img.height,
canvas = document.createElement('canvas'),
destWidth = Math.round(img.width * resizeMultiplier)
canvas.width = destWidth
canvas.height = destHeight
canvas.getContext('2d').drawImage(img, 0, 0, destWidth, destHeight)
if(to === 'DataURL') {
// console.log('working on DataURL', canvas.toDataURL(mimeType, quality));
resolve(canvas.toDataURL(mimeType, quality))
} else if(to === 'Blob') {
canvas.toBlob(blob => {
resolve(blob)
}, mimeType, quality)
} else {
reject( 'Wrong param to "value": allowed "DataURL" or "Blob"' )
}
} // img.onload end
img.src = result
} // reader.onload end
reader.readAsDataURL(file)
} )
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment