Image to base 64 on Angular

component.ts
--------------------------------
... 
const img = document.getElementById("imgurl") as HTMLElement;

function getBase64Image(imgUrl:any, callback:any) {
              var img = new Image();
              // onload fires when the image is fully loadded, and has width and height
              img.onload = function(){
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx:any = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0);
                var dataURL = canvas.toDataURL("image/png"),
                    dataURL = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");

                callback(dataURL); // the base64 string

              };

              // set attributes and src
              img.setAttribute('crossOrigin', 'anonymous'); //
              img.src = imgUrl;

 }
getBase64Image(imgurl, function(base64image:any){
              //  console.log(base64image);
               let imgshow = 'data:image/png;base64,'+base64image
               img.setAttribute("src",   imgshow);
});
page.html
---------------------------------------------------------
 <img id="imgurl"  ngSrc="logo.png" class="img-thumbnail card-img-top"  />
Share

You may also like...

Leave a Reply