2013-05-06 29 views
3

我有一個文件輸入,我用來獲取文件並將它變成一個blob。無論如何,我可以得到一個外部圖像網址,並把它變成一個blob?這裏是我使用僅僅用一個文件來做到這一點,代碼從<input type="file" />從外部圖像創建一個Blob url

//Process the file and resize it. 
     function processfile(file) { 

      if (!(/image/i).test(file.type)) { 
       alert("File " + file.name + " is not an image."); 
       return false; 
      } 

      // read the files 
      var reader = new FileReader(); 
      reader.readAsArrayBuffer(file); 

      reader.onload = function (event) { 
       // blob stuff 
       var blob = new Blob([event.target.result]); // create blob... 
       window.URL = window.URL || window.webkitURL; 
       var blobURL = window.URL.createObjectURL(blob); // and get it's URL 

       // helper Image object 
       var image = new Image(); 
       image.src = blobURL; 
       image.onload = function() { 

        for (var x = 0; x < self.ThumbSizes.length; x++) { 
         // have to wait till it's loaded 
         var resized = resizeMe(image, self.ThumbSizes[x]); // send it to canvas 
         var resized_blob = dataURItoBlob(resized); 
         uploadFile(resized_blob, self.ThumbSizes[x].Name); 
        } 
       } 
      }; 

不是傳遞文件通過我希望能夠構建這個代碼通過一個圖像的URL,並將其轉換成斑點。

+1

這是您正在尋找的解決方案的類型? http://stackoverflow.com/questions/934012/get-image-data-in-javascript – Nate 2013-05-07 00:33:20

回答

2

我希望它可以幫助你。 (我沒有運行它。)

function processfile(imageURL) { 
    var image = new Image(); 
    var onload = function() { 
     var canvas = document.createElement("canvas"); 
     canvas.width =this.width; 
     canvas.height =this.height; 

     var ctx = canvas.getContext("2d"); 
     ctx.drawImage(this, 0, 0); 

     canvas.toBlob(function(blob) { 
      // do stuff with blob 
     }); 
    }; 

    image.onload = onload; 
    image.src = imageURL; 
} 
+3

canvas.toBlob在Chrome等主流瀏覽器上不受支持,但你可以使用這個polyfill https://github.com/blueimp/JavaScript -Canvas對斑點 – Safareli 2014-09-28 12:50:55