2012-08-07 66 views
20

Estoy tratando de implementar un controlador de pegar para obtener una imagen del portapapeles del usuario. Quiero que esto se ejecute solo en Google Chrome, no me preocupan otros navegadores.Javascript: objeto Blob a base64

Esto es parte de un método que encontré en Internet y estoy tratando de adaptarlo.

// Get the items from the clipboard 
var items = e.clipboardData.items; 
    if (items) { 
    // Loop through all items, looking for any kind of image 
     for (var i = 0; i < items.length; i++) { 
      if (items[i].type.indexOf("image") !== -1) { 
       // We need to represent the image as a file, 
       var blob = items[i].getAsFile(); 
       // and use a URL or webkitURL (whichever is available to the browser) 
       // to create a temporary URL to the object 
       var URLObj = window.URL || window.webkitURL; 
       var source = URLObj.createObjectURL(blob); 
       createImage(source); 
       } 
      } 
     } 

el método funciona y puedo mostrar la imagen si uso mi "fuente" como el src de un objeto de imagen. El problema es que la fuente de la imagen en google chrome será algo como esto: blob:http://localhost:8080/d1328e65-ade2-45b3-a814-107cc2842ef9

Necesito enviar esta imagen al servidor, entonces quiero convertirla a una versión base64. Por ejemplo:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAArgAAAAjCAIAAADwnO7RAAAKMWlDQ1BJQ0MgUHJvZmlsZQAASImdlndUU9kWh8+9N71QkhCKlNBraFICSA29SJEuKjEJEErAkAAiNkRUcERRkaYIMijggKNDkbEiioUBUbHrBBlE1HFwFBuWSWStGd+8ee/Nm98f935rn73P3Wfvfda6AJD8gwXCTFgJgAyhWBTh58WIjYtnYAcBDPAAA2wA4HCzs0IW+EYCmQJ82IxsmRP4F726DiD5+yrTP4zBAP+flLlZIjEAUJiM5/L42VwZF8k4PVecJbdPyZi2NE3OMErOIlmCMlaTc/IsW3z2mWUPOfMyhDwZy3PO4mXw5Nwn4405Er6MkWAZF+cI+LkyviZjg3RJhkDGb+SxGXxONgAoktwu5nNTZGwtY5IoMoIt43kA4EjJX/DSL1jMzxPLD8XOzFouEiSniBkmXFOGjZMTi+HPz03ni8XM...iCIBWnh+P9w9C+9eMzvhCl1iOElK09ruc2wqGhfH/uKEV30FlJkmRZJklydFuW/FdwhYFCkCBBggQJEuS/gWC4FCRIkCBBggQZlmCgECRIkCBBggQZlmCgECRIkCBBggQZFmzhwoXXWoYgQYIECRIkyHUK5vF4rrUMQYIECRIkSJDrFHLktYOCBAkSJEiQIP/NkLt3777WMgT5thLstwoSJEiQ7zxYsEUhyJWxbdu2u++++1pLESRIkCBBvl6Csx6CBAkSJEiQIMPy3dkMOsg3T7A5KkiQIEG+8wQDhSBXTjBQCBIkSJDvPMGuhyBBggQJEiTIsFwXLQr9H6bOjtYeP2mONbOj2Hut9y6/x+nlJSBCQnXkgG3Brh8Q4lqbOpAmPDqUGShex9lPDlfB4sU5I97b/8kuevygYUgYsAksAPg9fkbDQN/e1kNvVw76nfYeiTCG6sjLd5fv58rsFmxRCBIkSJDvPP8f+HtxbDVRPI8AAAAASUVORK5CYII= 

En la primera parte del código, tengo un objeto blob que representa el archivo. ¿Cómo puedo usarlo para crear una representación base64? He intentado un par de métodos pero no obtengo la representación correcta.

Por favor, ¿alguien me puede ayudar?

+0

http://stackoverflow.com/questions/7650587/using-javascript-to-display-blob – jcolebrand

+0

http://stackoverflow.com/questions/ 6431281/save-png-canvas-image-to-html5-storage-javascript – jcolebrand

+0

jcolebrand Intenté usar la codificación base64 de la otra pregunta, pero recibo este error: Excepción: TypeError: Object # no tiene método ' reemplace ' Tal vez el tipo de letra sea diferente, así que no creo que mi pregunta esté duplicada ... porque las demás respuestas no me pueden ayudar en esta c Plaza bursátil norteamericana. O tal vez me estoy perdiendo algo ... – Rafael

Respuesta

30

Voy a responder mi propia pregunta en caso de que alguien llegue a esta página con el mismo problema.

La respuesta de Nick Retallack en esta página How does the paste image from clipboard functionality work in Gmail and Google Chrome 12+? hace exactamente lo que quiero.

Así que la nueva pieza de código es:

var items = e.clipboardData.items; 
if (items) { 
// Loop through all items, looking for any kind of image 
    for (var i = 0; i < items.length; i++) { 
     if (items[i].type.indexOf("image") !== -1) { 
      // We need to represent the image as a file, 
      var blob = items[i].getAsFile(); 

      var reader = new FileReader(); 
       reader.onload = function(event){ 
        createImage(event.target.result); //event.target.results contains the base64 code to create the image. 
       }; 
       reader.readAsDataURL(blob);//Convert the blob from clipboard to base64 
      } 
     } 
    } 
+0

¿Podría compartir cómo maneja la carga en php? http://stackoverflow.com/questions/18055422/how-to-receive-php-image-data-over-copy-n-paste-javascript-with-xmlhttprequest/18055837?noredirect=1#comment26445274_18055837 – poitroae

+0

Hola, he manejado esto en una aplicación Java. Tuve que usar DatatypeConverter.parseBase64Binary (myBase64Code) para obtener una representación de bytes de la imagen. Tal vez hay algo similar a esto en PHP. – Rafael

Cuestiones relacionadas