Transform html image into angular blob

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've tried:

  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'.

    
asked by anonymous 27.07.2018 / 19:15

1 answer

0

After a few hours of searching, I was able to find a function that fills 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;
  }
    
27.07.2018 / 19:57