Skip to content

Instantly share code, notes, and snippets.

@chriskoelle
Created December 16, 2014 20:06
Show Gist options
  • Save chriskoelle/ecdd96066a0d107dabcb to your computer and use it in GitHub Desktop.
Save chriskoelle/ecdd96066a0d107dabcb to your computer and use it in GitHub Desktop.
Use javascript and canvas to resize images from file input before upload
jQuery(function($) {
// Test for file API support.
var fileApiSuport = !!(window.File && window.FileReader );
/**
* Resize images that exceed the maximum size (in pixels)
* @param {object} input The file input.
* @param {Function} callback Callback function run after the image has been resized.
* @return {null}
*/
var maxImageSize = function(input, callback) {
var file = input.files[0];
// Make sure the file is an image and the file API is supported.
if( !file.type.match(/image.*/) || !fileApiSuport ) {
callback(file);
return;
}
var img = document.createElement("img"),
reader = new FileReader();
// Wait until the image is loaded (after file reader is loaded)
img.onload = function() {
var canvas = document.createElement('canvas'),
max_size = 2000,
width = img.width,
height = img.height,
ctx = null,
dataurl = null;
// If the image fits within the constraints, use the original image
if( width <= max_size && height <= max_size ) {
callback(file);
return;
// Calculate the new image size
} else {
if(width > height) {
height *= max_size / width;
width = max_size;
} else {
width *= max_size / height;
height = max_size;
}
}
// Use canvas to resize the image.
canvas.width = width;
canvas.height = height;
ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
if(canvas.toBlob) {
canvas.toBlob(function(blob) {
if(blob && blob.type === file.type) {
callback(blob);
} else {
callback(file);
}
}, file.type, 80);
} else {
callback(file);
}
return;
};
// Wait until after the file reader has loader.
reader.onload = function(e) { img.src = e.target.result; };
reader.readAsDataURL(file);
};
var fileInputChanged = function() {
var finput = this;
maxImageSize(finput, function(file) {
// Do Something with the file :)
});
};
someInput.on('change', fileInputChanged);
});
/**
* Canvas to Blob
* @link https://github.com/blueimp/JavaScript-Canvas-to-Blob
*/
!function(a){"use strict";var b=a.HTMLCanvasElement&&a.HTMLCanvasElement.prototype,c=a.Blob&&function(){try{return Boolean(new Blob)}catch(a){return!1}}(),d=c&&a.Uint8Array&&function(){try{return 100===new Blob([new Uint8Array(100)]).size}catch(a){return!1}}(),e=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder,f=(c||e)&&a.atob&&a.ArrayBuffer&&a.Uint8Array&&function(a){var b,f,g,h,i,j;for(b=a.split(",")[0].indexOf("base64")>=0?atob(a.split(",")[1]):decodeURIComponent(a.split(",")[1]),f=new ArrayBuffer(b.length),g=new Uint8Array(f),h=0;h<b.length;h+=1)g[h]=b.charCodeAt(h);return i=a.split(",")[0].split(":")[1].split(";")[0],c?new Blob([d?g:f],{type:i}):(j=new e,j.append(f),j.getBlob(i))};a.HTMLCanvasElement&&!b.toBlob&&(b.mozGetAsFile?b.toBlob=function(a,c,d){d&&b.toDataURL&&f?a(f(this.toDataURL(c,d))):a(this.mozGetAsFile("blob",c))}:b.toDataURL&&f&&(b.toBlob=function(a,b,c){a(f(this.toDataURL(b,c)))})),"function"==typeof define&&define.amd?define(function(){return f}):a.dataURLtoBlob=f}(this);
@chriskoelle
Copy link
Author

Notes

  • Canvas to Blob does not work correctly in some older Android browsers (file type is not retained)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment