Transform html image into angular blob

Asked

Viewed 286 times

0

I have the following image:

<img id="preview" class="cropped rounded-circle align-center animated fadeIn" width="220px" height="220px">

I need to pass it to a function that will convert to base 64, but to convert to base 64, my image must be in blob before: What I tried to:

  handleCropSelect(){
      var file = document.getElementById("preview")
      var reader = new FileReader();
      reader.onload = this._handleReaderLoaded.bind(this);
      reader.readAsBinaryString(file);
  }

What I get:

Argument of type 'Htmlelement' is not Assignable to Parameter of type 'Blob'. Property 'size' is Missing in type 'Htmlelement'.

1 answer

0


After a few hours of searching, I was able to find a function that meets my need:

  getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.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,/, "");
  }

  handleCropSelect(){
      var base64 = this.getBase64Image(document.getElementById("preview"));
      this.base64textString = base64;
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.