Last active
September 21, 2021 05:03
-
-
Save theanam/de7efd7deb800a8157cade7d672fb6c7 to your computer and use it in GitHub Desktop.
A small JavaScipt function to resize image in frontend and return a new JPEG file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/**** | |
Creatd by Anam Ahmed (https://anam.co) | |
Sample Use: | |
document.querySelector("input[type=file]").addEventListener("change",function(e){ | |
if(e.target.files.length){ | |
_resample(e.target.files[0],1000,function(response){ | |
console.log(response); // returns an object: {stats:<compression stats>,file:output file} | |
}); | |
} | |
}); | |
****/ | |
function _resample(imageFile,SIZE_CAP,callbackFunction){ | |
if(!imageFile.type.match(/^image\//)){ | |
return console.error("File should be an image file to resample"); | |
} | |
var _fr = new FileReader(); | |
var _im = new Image(); | |
_fr.readAsDataURL(imageFile); | |
// File reader Events | |
_fr.onload = function(){ | |
_im.src = _fr.result; | |
} | |
_fr.onerror = function(){ | |
console.error("Cannot load Image file"); | |
} | |
// Image Events | |
_im.onload = function(){ | |
if(_im.width<=1000 && _im.height<=1000){ | |
callbackFunction(imageFile); | |
} | |
// Calculate new Image Size | |
var originalDimentions = { | |
width: _im.width, | |
height:_im.height | |
} | |
var largstSide = "width"; | |
var smallestSide = "height"; | |
if(originalDimentions.height>originalDimentions.width){ | |
largstSide = "height"; | |
smallestSide = "width"; | |
} | |
var smallestDimention = Math.floor((originalDimentions[smallestSide]/originalDimentions[largstSide])*SIZE_CAP); | |
var largestDimention = SIZE_CAP; | |
var newSize = {} | |
newSize[largstSide] = largestDimention; | |
newSize[smallestSide] = smallestDimention; | |
// Create Canvas with the new Size | |
var cvs = document.createElement("canvas"); | |
cvs.width = newSize.width; | |
cvs.height = newSize.height; | |
var ctx = cvs.getContext("2d"); | |
ctx.drawImage(_im,0,0,originalDimentions.width,originalDimentions.height,0,0,newSize.width,newSize.height); | |
window.cvs = cvs; | |
window.ctx = ctx; | |
cvs.toBlob(function(blobData){ | |
var filename_base = imageFile.name.split("."); | |
filename_base.pop(); | |
var fileName = filename_base.join("_")+".jpeg"; | |
var newConstructedFile = new File([blobData],fileName,{type:"image/jpeg"}); | |
var stats = { | |
source_file_size:imageFile.size, | |
compressed_file_size:newConstructedFile.size, | |
ratio: (newConstructedFile.size/imageFile.size)*100 | |
} | |
callbackFunction({ | |
file:newConstructedFile, | |
stats:stats | |
}); | |
},"image/jpeg",1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment