如何将图像转换为angular5中的base 64?

时间:2018-04-18 20:08:49

标签: typescript ionic-framework ionic3

如何将图像转换为angular5中的base 64? 该图片是来自facebook或google authentification api的网址。

我做错了什么?

   getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.src.width;
canvas.height = img.src.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

//用法

    var url=" https://www.livemint.com/rf/Image-621x414/LiveMint/Period2/2017/06/12/Photos/Opinion/telecom-km8--621x414@LiveMint.JPG";


var base64 = this.getBase64Image(url);

//错误

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'width' of undefined TypeError: Cannot read property 'width' of undefined

1 个答案:

答案 0 :(得分:0)

如果您的图像为File,则可以使用FileReader轻松将其转换为base64:

convert(file: File): string {
    const reader: FileReader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = (): void => {
        const base64String: string = (reader.result as string).match(
            /.+;base64,(.+)/
        )[1];
        return base64String;
    };
}