2014-04-23 39 views
10

我正在爲移動設備建立一個網站,該網站使用angular-file-upload.min.js從移動設備圖像庫上傳圖像。angularjs在上傳前壓縮圖像

的html代碼:

<div> 
    <div class="rating-camera-icon"> 
     <input type="file" accept="image/*" name="file" ng-file- 
     select="onFileSelect($files)"> 
    </div> 
    <img ng-show="fileName" ng-src="server/{{fileName}}" width="40" 
    style="margin-left:10px"> 
</div> 

代碼:

$scope.onFileSelect = function($files) { 
     for (var i = 0; i < $files.length; i++) { 
      var file = $files[i]; 
      if (!file.type.match(/image.*/)) { 
       // this file is not an image. 
      }; 
      $scope.upload = $upload.upload({ 
       url: BASE_URL + 'upload.php', 
       data: {myObj: $scope.myModelObj}, 
       file: file 
      }).progress(function(evt) { 
        // console.log('percent: ' + parseInt(100.0 * evt.loaded/evt.total)); 
        // $scope.fileProgress = evt.loaded/evt.total * 100.0; 
       }).success(function(data, status, headers, config) { 
        // file is uploaded successfully 
        $scope.fileName = data; 
       }); 
     } 
    }; 

上傳是在移動設備中非常緩慢。我如何壓縮文件?

+0

如果你不使用原生應用程序,你可以不壓縮文件也最喜歡的JPG圖像已經就我知道的壓縮有什麼你可以做。 –

+0

如果你之前上傳這可能幫助尋找圖像處理:http://stackoverflow.com/questions/2434458/image-resizing-client-side-with-javascript-before-upload-to-the-server –

回答

0

您可以嘗試將圖像存儲在畫布上,然後轉換爲data64,然後上載數據字符串。 我在POC中做了一個這樣的事情,在ios上有一個關於大圖像的bug,就像你在畫布上用相機拍攝的一樣,但是整體效果很好......類似的東西;

file = files[0]; 
try { 
    var URL = window.URL || window.webkitURL, 
     imgURL = URL.createObjectURL(file); 
    showPicture.src = imgURL; 
    imgBlobToStore = imgURL; 
    if(AppData.supports_html5_storage()) {  
    var canvas = document.getElementById('storingCanvas') , 
     ctx = canvas.getContext('2d'), 
     img = new Image(), 
     convertedFile; 
    img.src = imgBlobToStore; 
    img.onload = function() {  
     canvas.width = img.width; 
     canvas.height= img.height; 
     ctx.drawImage(img, 0,0,img.width, img.height); 
     convertedFile = canvas.toDataURL("image/jpeg"); //or png 
     //replace with angular storage here 
     localStorage.setItem($('.pic').attr('id'), convertedFile); 
    }; 
    }, 
} 
3

將圖像字符串化爲base-64文本格式非常好,但它會花費很少的時間,並且不會對它進行壓縮。實際上它可能比原始圖像明顯更大。不幸的是,您的瀏覽器也不會gzip上傳。他們當然可以處理gzipped下載。你當然可以嘗試使用一些純粹的JS解決方案來對文本本身進行gzip。展望在GitHub上,你可以找到這樣的事情 - https://github.com/beatgammit/gzip-js然而,這需要一定的時間,以及並沒有保證圖像的壓縮文字版本是任何比你附上原始JPEG小。

一個原生移動應用可能會決定使用一些本地代碼的JPEG或PNG優化前發送合適的話(基本上重新採樣圖像),但在JavaScript這樣做了,在這個時間點,似乎有潛在問題。鑑於阿特伍德的法律(最終用JavaScript編寫所有內容)當然可以完成,但在2014年年中的這一點上並不是這樣。

-2

作爲替代的編程解決方案 - 如果正在由設備相機上傳創建你的形象,那麼爲什麼不乾脆改變相機的分辨率。最小分辨率可能比最大分辨率小10倍,這可能適用於許多情況。