Skip to content

Instantly share code, notes, and snippets.

@JeffGuKang
Last active August 18, 2019 12:37
Show Gist options
  • Save JeffGuKang/dd8fa2447c11430cee2542793ca748c1 to your computer and use it in GitHub Desktop.
Save JeffGuKang/dd8fa2447c11430cee2542793ca748c1 to your computer and use it in GitHub Desktop.
Image resize and orientation
/**
* Resie and auto rotate
* using https://github.com/blueimp/JavaScript-Load-Image
* @param {file from input} file
* @param {number} maxSize
*/
function ResizeImage(file, maxSize=1024) {
return new Promise(function(resolve, reject) {
if (window.File && window.FileReader && window.FileList && window.Blob) {
/**
* https://zest0804.tistory.com/entry/앱에서-웹으로-이미지-업로드-할-경우-이미지-exif-정보에-따라-회전하는-이슈
*/
loadImage(
file,
function(canvas, data) {
dataurl = canvas.toDataURL("image/jpeg");
var imgtype = dataurl.split(';');
// 이미지의 컨텐츠 유형을 얻는다.
var contentType = imgtype[0].split(':')[1];
var blob = dataURLToBlob(dataurl);
var resizedImage = new File([blob], "image.jpg", {lastModified: new Date(), type: 'image/jpeg'});
resolve({ resizedImage, dataurl });
},
{
maxWidth: maxSize,
maxHeight: maxSize,
orientation: true,
canvas: true,
}
);
} else {
reject('The File APIs are not fully supported in this browser.');
}
})
}
/* Utility function to convert a canvas to a BLOB */
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType});
}
/* End Utility function to convert a canvas to a BLOB */
function blobToFile(theBlob, fileName = 'image.jpg'){
//A Blob() is almost a File() - it's just missing the two properties below which we will add
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment