如何在Angular中将实时图像URL转换为Blob?

9
我正在使用 Angular 7,我的需求是需要获取图片的 宽度高度大小(以 kb 或 mb 为单位),同时我也在尝试将其转换为 blob
我已经尝试了下面的代码,但是没有得到准确的输出:
var img_url = "http://snook.ca/files/mootools_83_snookca.png";


 var blob = new Blob([img_url]);

 let reader = new FileReader;

 reader.readAsDataURL(blob); // read file as data url
 reader.onload = () => { // when file has loaded
    console.log(reader.result)
    var img:any = new Image();
    img.src = reader.result;

    img.onload = () => {

      this.uploaded_image_width = img.width; //to get image width
      this.uploaded_image_height = img.height;  //to get image height           

      this.uploaded_image_url = reader.result; //to get blob image
      console.log(reader.result)          
    };          
  } 

当我安慰blob数据时,数据出现了错误(console.log(reader.result)),而且在img.onload函数内部没有执行。

我参考了这个fiddle来实现这个功能: http://jsfiddle.net/guest271314/9mg5sf7o/


你必须设置图像的源以加载它。只有当图像具有src时,才会调用onload。问题在于你在声明钩子之前设置了源:将该行移动到钩子下面,然后你就可以正常运行了! - user4676340
那是针对音频而不是图像的,但实际上它们是一样的。 - Kaiido
请仔细查看我的问题,它与@Kaiido的不同。 - VinoCoder
对我来说问题是图片不在我的本地或上传的图片中,而是在@Kaiido的实时图片中。 - VinoCoder
问题在于你在一个问题中提出了3个问题...要从这个URL获取Blob需要目标服务器允许你执行ajax请求,然后只需要fetch(url).then(r=>r.blob)。我又添加了关于你问题的另一个链接,但再次强调,为了成功,目标服务器必须允许你这样做。 - Kaiido
显示剩余2条评论
1个回答

1
你可以尝试这样做。我希望它能对你有所帮助。
var img = new Image();
img.onload = function(){
    alert( this.width+' '+ this.height );
};
img.src = "http://lorempixel.com/output/city-q-c-250-250-1.jpg";

1
我该如何获取该图像的Blob值? - VinoCoder
首先,您需要将图像转换为base64格式,然后再将其转换为blob格式。以下是将图像转换为blob格式的示例链接:https://gist.github.com/davoclavo/4424731 - Yash Rami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接