angularjs在上传之前压缩图像

angularjs compress image before upload

本文关键字:压缩 图像 angularjs      更新时间:2023-09-26

我正在为移动设备建立一个网站,该网站使用angular-file-upload.min.js从移动设备图像库上传图像。

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;
                });
        }
    };

在移动设备中上传速度非常慢。如何压缩文件?

将图像字符串化为base-64文本格式是很好的,但这需要很小的时间,而且肯定不会压缩它。事实上,它可能会明显大于原始图像。不幸的是,你的浏览器也不会gzip上传。它们当然可以处理gzip下载。您当然可以尝试使用一些纯JS解决方案对文本本身进行gzip。在github上你可以找到这样的东西-https://github.com/beatgammit/gzip-js然而,这也需要一些时间,并且不能保证图像的压缩文本版本比您附加的原始JPEG小。

如果合适的话,原生移动应用程序可能会决定在发送之前使用一些原生代码JPEG或PNG优化(基本上是对图像进行重新采样),但在这个时候用JavaScript这样做似乎有潜在的问题。考虑到阿特伍德的定律(最终用JavaScript编写所有内容),这当然是可以做到的,但在2014年年中的这个时候却不是。

您可以尝试将图像存储在画布上,然后转换为data64,然后上传数据字符串。我在POC中做了这样的事情,ios中有一个错误,认为大图像是你在画布上可以用相机拍摄的图像,但总体效果很好。。。类似的东西;

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);
    };
  }, 
}

有几个库可以在客户端为您执行此操作。

  • https://github.com/oukan/angular-image-compress
  • https://github.com/sammychl/ng-image-compress
  • http://angularscript.com/client-side-image-compress-directive-with-angular/

作为程序化解决方案的替代方案,如果您的图像是由设备相机创建以上传的,那么为什么不简单地更改相机的分辨率呢。最小分辨率可能比最大分辨率小10倍,这可能适用于许多情况。