Ver Mensaje Individual
  #1 (permalink)  
Antiguo 27/01/2015, 14:42
underwebinfo
 
Fecha de Ingreso: septiembre-2012
Ubicación: Buenos aires
Mensajes: 110
Antigüedad: 11 años, 7 meses
Puntos: 9
Pregunta [Problema] FileReader multiples imagenes

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
  1. (function($){
  2.    
  3.     // OBJECTS
  4.     var _RESIZER = {}, _methods = {}, _tools = {} , _polyfill = {}, _support = {}, _blob = false;
  5.    
  6.     // ----- ----- RESIZER
  7.     _RESIZER.init = function(){
  8.    
  9.         try{
  10.  
  11.             // Comprobate if support canvas and fileReader
  12.             _support.init();
  13.            
  14.         }catch(e){
  15.        
  16.             console.log(e);
  17.        
  18.         }
  19.            
  20.     }
  21.  
  22.     // OPTIONS
  23.     _default = {
  24.        
  25.         // General
  26.         _lector : false,
  27.         _error  : [],
  28.        
  29.         // OPTIONS THE PREVIEW
  30.         thumb: {
  31.            
  32.             file        : '',
  33.             max         : [1920,1080],
  34.             min         : [0,0],
  35.             blob        : false,
  36.             mime        : 'image/jpeg',
  37.            
  38.             onprogress  : function(){},
  39.             onLoaded    : function(){}
  40.            
  41.         }
  42.        
  43.     };
  44.    
  45.     // METHODS
  46.     _methods.thumb = function(options){
  47.        
  48.         try{
  49.        
  50.             // INIT
  51.             _RESIZER.init();           
  52.  
  53.             // Options
  54.             var _options = $.extend(_default.thumb,options);
  55.                        
  56.             // Get type from file
  57.             if(!_options.file)             
  58.                 new Exception('[_RESIZER ERROR]: File element is require where what is the principal image to cropping.');
  59.                        
  60.             // Progress
  61.             _default._lector.onprogress= _options.onprogress;
  62.            
  63.             // Cuando el lector esta listo
  64.             _default._lector.onload = function(e){
  65.            
  66.                 // Base64 Image obtain input
  67.                 var _base = e.srcElement.result;
  68.                 var _image= document.createElement('img');
  69.                
  70.                 // Insert image data
  71.                 _image.src = _base;
  72.  
  73.                 // onLoad image
  74.                 _image.onload = function(){
  75.                    
  76.                     // Aspect Radio
  77.                     if(this.width > this.height)
  78.                        
  79.                         // Reduccion del width si supera el tamaño
  80.                         if(this.width > _options.max[0]){
  81.                            
  82.                             this.height *= _options.max[0] / this.width;
  83.                             this.width   = _options.max[0];
  84.                            
  85.                         }
  86.                        
  87.                     else{
  88.                        
  89.                         // Reduccion del width si supera el tamaño
  90.                         if(this.height > _options.max[1]){
  91.                            
  92.                             this.width *= _options.max[1] / this.height;
  93.                             this.height = _optionns.max[1];
  94.                            
  95.                         }
  96.                        
  97.                     }
  98.                    
  99.                     // Canvas
  100.                     var _canvas = document.createElement("canvas");
  101.                         _canvas.width = this.width;
  102.                         _canvas.height= this.height;
  103.                    
  104.                     // Canvas 2d   
  105.                     var _context = _canvas.getContext("2d");;
  106.                         _context.drawImage(this,0,0,this.width,this.height);
  107.                        
  108.                     // Return data final
  109.                     var file = _canvas.toDataURL(_options.mime);
  110.                                        
  111.                     // Retornamos en la llamada de onloaded
  112.                     _options.onLoaded(file);
  113.                    
  114.                     // Asignamos el blob
  115.                     _blob = file;
  116.                    
  117.                 }
  118.                                
  119.             }
  120.            
  121.             // Read file
  122.             _default._lector.readAsDataURL(_options.file);
  123.            
  124.         }catch(e){
  125.            
  126.             console.log('RESIZER - THUMB: '+e);
  127.            
  128.         }
  129.        
  130.     }
  131.  
  132.     // ---- Support
  133.     _support.init = function(){
  134.    
  135.         // Comprobamos que apis estan disponibles
  136.         if(window.File && window.FileReader && window.FileList && window.Blob)
  137.             // Lecor
  138.             _default._lector = new FileReader();
  139.            
  140.         else
  141.             // Lector
  142.             _default._error.push('[_RESIZER SUPPORT:] Not available the api\'s for File\'s html5.');
  143.            
  144.         // Comprobamos si canbas esta disponible
  145.         if(!(!!window.HTMLCanvasElement))
  146.             // Canvas
  147.             _default._error.push('[_RESIZER SUPPORT:] Not available the canvas for javascript in this browser.');
  148.        
  149.        
  150.         // Polyfill
  151.         if(!HTMLCanvasElement.prototype.toBlob)
  152.             _polyfill.toBlob();
  153.        
  154.         // Comprobamos si hubo errores retornamos false
  155.         if(_default._error.lenght)
  156.             return false;
  157.            
  158.     }
  159.  
  160.     // ---- TOOLS;
  161.     _tools.toBlob = function(data,mime){
  162.        
  163.         // Decodifica dataURL
  164.         var binary = atob(data.split(',')[1]);
  165.  
  166.         // Se transfiere a un array de 8-bit unsigned
  167.         var array = [];
  168.         for(var i = 0; i < binary.length; i++) {
  169.             array.push(binary.charCodeAt(i));
  170.         }
  171.         // Retorna el objeto Blob
  172.         return new Blob([new Uint8Array(array)], {type: mime});
  173.        
  174.     }
  175.    
  176.     // ---- POLIFYLL
  177.     _polyfill= {}
  178.    
  179.     _polyfill.toBlob = function(){
  180.    
  181.         Object.defineProperty(HTMLCanvasElement.prototype,'toBlob',{
  182.  
  183.             value: function(callback,type,quality){
  184.            
  185.                 var binStr = atob(this.toDataURL(type, quality).split(',')[1] ),len = binStr.length,arr = new Uint8Array(len);
  186.  
  187.                 for (var i=0; i<len; i++ ) { arr[i] = binStr.charCodeAt(i); }
  188.  
  189.                 callback( new Blob( [arr], {type: type || 'image/png'} ) );
  190.             }
  191.        
  192.         });
  193.        
  194.     }
  195.    
  196.     $.Resizer = function(){ return this };
  197.     $.Resizer.thumb = function(options){
  198.    
  199.         // Llamamos a la funcion
  200.         _methods.thumb(options);
  201.  
  202.         var _options = $.extend(_default.thumb,options);
  203.        
  204.         // Retornamos el file
  205.         if(_options.blob)
  206.             return _tools.toBlob(_blob,_options.mime);
  207.         else
  208.             return _blob;
  209.        
  210.     }
  211.    
  212. })(jQuery);


Esta es la forma en la que lo llamo
Código Javascript:
Ver original
  1. // Variable
  2.         var data = $.Resizer.thumb({
  3.                
  4.             file    : file,
  5.             max     : [1920,1080],
  6.             mime    : 'image/jpg',
  7.             blob    : true,
  8.            
  9.         });