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 類型返回給 服務端


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM