Last active
March 9, 2016 14:59
-
-
Save tiger154/9a842f0c02584325c155 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* | |
* $('#Files').change(function (event) { | |
* var file = this.files[0]; | |
* var img = $('#preview-img'); | |
* var loader = $('#preview-loader'); | |
* e.g : $.thumb(file, img, loader) | |
* }); | |
* | |
* | |
* When change file event we can use thumb image by html5 with FileReader, Canvas | |
* - It resize by ratio of file's with and height | |
* @param file : (jQuery object) target file input filed | |
* @param img : (jQuery object) img input filed which display thumb | |
* @param loader (jQuery object) while loading image it shows loading messages | |
* @param max_width (int) | |
* @param max_height (int) | |
*/ | |
(function($){ | |
$.thumb = function(file, img, loader, max_width, max_height){ | |
if (!file.type.match('image.*')) { return false; } | |
max_width = typeof max_width !== 'undefined' ? max_width : 150; | |
max_height = typeof max_height !== 'undefined' ? max_height : 100; | |
var $img = img; // jQuery object | |
var img = img[0]; // Dom object | |
if (file) { | |
loader.show(); | |
var reader = new FileReader(); | |
reader.readAsDataURL(file); | |
reader.onload = function (e) { | |
img.src = e.target.result; // show local image | |
// create thumb | |
var tempImage = new Image(); | |
tempImage.src = reader.result; | |
tempImage.onload = function () { | |
// create canvas obj to resize | |
var canvas = document.createElement("canvas"); | |
var canvasContext = canvas.getContext("2d"); | |
var MAX_WIDTH = max_width; | |
var MAX_HEIGHT = max_height; | |
var width = img.width; | |
var height = img.height; | |
if (width > height) { | |
if (width > MAX_WIDTH) { | |
height *= MAX_WIDTH / width; | |
width = MAX_WIDTH; | |
} | |
} else { | |
if (height > MAX_HEIGHT) { | |
width *= MAX_HEIGHT / height; | |
height = MAX_HEIGHT; | |
} | |
} | |
canvas.width = width; | |
canvas.height = height; | |
// draw image on canvas | |
canvasContext.drawImage(this, 0, 0, width, height); | |
// transform the image to data-uri | |
var dataURI = canvas.toDataURL('image/png'); | |
// show thumb | |
img.src = dataURI; | |
} | |
$img.fadeIn(); | |
loader.hide(); | |
} | |
} | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment