URL to Blob

 1 public urlToBlob(url) {
 2         const self = this;
 3         const image = new Image();
 4         image.crossOrigin = '';
 5         image.src = url;
 6         image.onload = function () {
 7             // 图片的绝对路径地址 转换成base64编码 如下代码:
 8             const canvas = document.createElement('canvas');
 9             canvas.width = image.width;
10             canvas.height = image.height;
11             const ctx = canvas.getContext('2d');
12             ctx.drawImage(image, 0, 0, image.width, image.height);
13             // canvas.toBlob((res) => {
14             //     console.log(res);
15             //     self.communityFormData.delete('image');
16             //     self.communityFormData.append('image', res);
17             //     console.log(self.communityFormData.get('image'));
18             // });
19             const ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase();
20             const dataURL = canvas.toDataURL('image/' + ext);
21             const type = 'image/' + ext;
22             console.log(dataURL);
23             const bytes = window.atob(dataURL.split(',')[1]); // 去掉url的头,并转换为byte
24             console.log(bytes);
25             // 处理异常,将ascii码小于0的转换为大于0
26             const ab = new ArrayBuffer(bytes.length);
27             console.log(ab);
28             const ia = new Uint8Array(ab);
29             console.log(ia);
30             for (let i = 0; i < bytes.length; i++) {
31                 ia[i] = bytes.charCodeAt(i);
32             }
33             console.log(ia);
34             const tempBlob = new Blob([ia], { type: type });
35             self.communityFormData.delete('image');
36             self.communityFormData.append('image', tempBlob);
37             console.log(tempBlob);
38         };
39     }

将服务端传过来的图片绝对地址转成 Blob 类型返回给 服务端

posted @ 2018-09-17 14:07  海无泪  阅读(2860)  评论(0编辑  收藏  举报