简体   繁体   English

在Angularjs中上传文件之前获取image dataUrl | ng-file-upload

[英]Get image dataUrl before file upload in Angularjs | ng-file-upload

I'm resizing the image before upload it to the server using HTML5 Canvas. 我正在调整图像的大小,然后使用HTML5 Canvas将其上传到服务器。

Also I use Angular's module ng-file-upload . 我也使用Angular的模块ng-file-upload

Stack on getting dataUrl of resized image. 堆栈上获取调整大小后的图像的dataUrl。 Console returns data:, 控制台返回data:,

What could be the problem here? 这可能是什么问题?

HTML 的HTML

<input type="file" ngf-select ng-model="files">
<img ngf-src="files[0]">

JS JS

$scope.upload = function (files) {
    if (files && files.length==1) {
        var file = files[0];    

        var img = document.createElement("img");
        var canvas = document.createElement("canvas");
        var reader = new FileReader();
        reader.onload = function(e) {img.src = e.target.result};
        reader.readAsDataURL(file);

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

        var MAX_WIDTH = 200;
        var MAX_HEIGHT = 150;
        var width = img.width;
        var height = img.height;

        if (width > height) {
            if (width > MAX_WIDTH) {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
             }
        } else {
            if (height > MAX_HEIGHT) {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
             }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas.toDataURL("image/png");
        console.log( dataurl );
        ...

He had the same problem and solve it with: 他有同样的问题,并通过以下方法解决:

 $scope.upload = function (files) { if (files && files.length==1) { var file = files[0]; var URL = window.URL || window.webkitURL; var srcTmp = URL.createObjectURL(file); var img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = srcTmp; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM