Hola amigos que tal estuve haciendo un plugin para reducir el tamaño a las imagenes con el objeto FileReader(); y verdaderamente me quede pasmado con lo que me esta sucediendo:
Tengo 2 inputs files en los cuales selecciono una imagen y al enviar al servidor toma la imagen la carga y la redimensiona teniendo en cuenta un limite de tamaño.
Ahora que pasa.
Cuando obtengo los archivos blob los 2 son iguales sin importar que los inputs tengan distintas imagenes siempre me toma la primera.
Este es el plugin
Código Javascript
:
Ver original(function($){
// OBJECTS
var _RESIZER = {}, _methods = {}, _tools = {} , _polyfill = {}, _support = {}, _blob = false;
// ----- ----- RESIZER
_RESIZER.init = function(){
try{
// Comprobate if support canvas and fileReader
_support.init();
}catch(e){
console.log(e);
}
}
// OPTIONS
_default = {
// General
_lector : false,
_error : [],
// OPTIONS THE PREVIEW
thumb: {
file : '',
max : [1920,1080],
min : [0,0],
blob : false,
mime : 'image/jpeg',
onprogress : function(){},
onLoaded : function(){}
}
};
// METHODS
_methods.thumb = function(options){
try{
// INIT
_RESIZER.init();
// Options
var _options = $.extend(_default.thumb,options);
// Get type from file
if(!_options.file)
new Exception('[_RESIZER ERROR]: File element is require where what is the principal image to cropping.');
// Progress
_default._lector.onprogress= _options.onprogress;
// Cuando el lector esta listo
_default._lector.onload = function(e){
// Base64 Image obtain input
var _base = e.srcElement.result;
var _image= document.createElement('img');
// Insert image data
_image.src = _base;
// onLoad image
_image.onload = function(){
// Aspect Radio
if(this.width > this.height)
// Reduccion del width si supera el tamaño
if(this.width > _options.max[0]){
this.height *= _options.max[0] / this.width;
this.width = _options.max[0];
}
else{
// Reduccion del width si supera el tamaño
if(this.height > _options.max[1]){
this.width *= _options.max[1] / this.height;
this.height = _optionns.max[1];
}
}
// Canvas
var _canvas = document.createElement("canvas");
_canvas.width = this.width;
_canvas.height= this.height;
// Canvas 2d
var _context = _canvas.getContext("2d");;
_context.drawImage(this,0,0,this.width,this.height);
// Return data final
var file = _canvas.toDataURL(_options.mime);
// Retornamos en la llamada de onloaded
_options.onLoaded(file);
// Asignamos el blob
_blob = file;
}
}
// Read file
_default._lector.readAsDataURL(_options.file);
}catch(e){
console.log('RESIZER - THUMB: '+e);
}
}
// ---- Support
_support.init = function(){
// Comprobamos que apis estan disponibles
if(window.File && window.FileReader && window.FileList && window.Blob)
// Lecor
_default._lector = new FileReader();
else
// Lector
_default._error.push('[_RESIZER SUPPORT:] Not available the api\'s for File\'s html5.');
// Comprobamos si canbas esta disponible
if(!(!!window.HTMLCanvasElement))
// Canvas
_default._error.push('[_RESIZER SUPPORT:] Not available the canvas for javascript in this browser.');
// Polyfill
if(!HTMLCanvasElement.prototype.toBlob)
_polyfill.toBlob();
// Comprobamos si hubo errores retornamos false
if(_default._error.lenght)
return false;
}
// ---- TOOLS;
_tools.toBlob = function(data,mime){
// Decodifica dataURL
var binary = atob(data.split(',')[1]);
// Se transfiere a un array de 8-bit unsigned
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
// Retorna el objeto Blob
return new Blob([new Uint8Array(array)], {type: mime});
}
// ---- POLIFYLL
_polyfill= {}
_polyfill.toBlob = function(){
Object.defineProperty(HTMLCanvasElement.prototype,'toBlob',{
value: function(callback,type,quality){
var binStr = atob(this.toDataURL(type, quality).split(',')[1] ),len = binStr.length,arr = new Uint8Array(len);
for (var i=0; i<len; i++ ) { arr[i] = binStr.charCodeAt(i); }
callback( new Blob( [arr], {type: type || 'image/png'} ) );
}
});
}
$.Resizer = function(){ return this };
$.Resizer.thumb = function(options){
// Llamamos a la funcion
_methods.thumb(options);
var _options = $.extend(_default.thumb,options);
// Retornamos el file
if(_options.blob)
return _tools.toBlob(_blob,_options.mime);
else
return _blob;
}
})(jQuery);
Esta es la forma en la que lo llamo
Código Javascript
:
Ver original// Variable
var data = $.Resizer.thumb({
file : file,
max : [1920,1080],
mime : 'image/jpg',
blob : true,
});