簡體   English   中英

將base64圖像數據轉換為angularjs中的圖像文件

[英]Convert base64 image data to image file in angularjs

在 angularjs 中將 base64 文件轉換為圖像時得到損壞的文件 誰能建議我如何在 angularjs 中將 base64 文件轉換為圖像

我正在使用這種方法將 base64 文件轉換為圖像

var imageBase64 = "image base64 data";
var blob = new Blob([imageBase64], {type: 'image/png'});

從這個 blob,您可以生成文件對象。

var file = new File([blob], 'imageFileName.png');

首先,您將 dataURL 轉換為 Blob 執行此操作

var blob = dataURItoBlob(imageBase64);

function dataURItoBlob(dataURI) {

            // convert base64/URLEncoded data component to raw binary data held in a string
            var byteString;
            if (dataURI.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(dataURI.split(',')[1]);
            else
                byteString = unescape(dataURI.split(',')[1]);

            // separate out the mime component
            var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

            // write the bytes of the string to a typed array
            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            return new Blob([ia], {type:mimeString});
        }

然后

var file = new File([blob], "fileName.jpeg", {
            type: "'image/jpeg'"
          });

除了一點之外,您的代碼看起來還可以:

您提供給 Blob 對象的數據不是 Blob 數據,而是 base64 編碼的文本。 您應該在插入之前解碼數據。

一旦我不知道您想要哪個 API,我將使用一個名為 decodeBase64 的偽函數,我們將理解它執行 Base64 編碼的逆操作(在 web 中有許多此函數的實現)。

您的代碼應如下所示:

// base64 already encoded data
var imageBase64 = "image base64 data";

//this is the point you should use
decodedImage = decodeBase64(imageBase64)

//now, use the decodedData instead of the base64 one
var blob = new Blob([decodedImage], {type: 'image/png'});

///now it should work properly
var file = new File([blob], 'imageFileName.png');

無論如何,一旦您還沒有使用,我就看不到在那里使用 AngularJS 的必要性。

在 Angular 8 中需要這個,所以我將答案稍微修改為打字稿並直接修改為文件,因為您擁有數據字符串中的 mimetype,您不妨使用它來創建文件。

dataURItoBlob(dataURI : any, fileName : string) : File{

    // convert base64/URLEncoded data component to a file
    var byteString;
   if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
   else
       byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
       ia[i] = byteString.charCodeAt(i);
    }

    return new File([ia],fileName, {type:mimeString});
}

所有學分都歸於@byteC0de,答案是https://stackoverflow.com/a/35401651/1805974

我在這里發布答案的唯一原因是因為谷歌一直將我發送到此頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM