convert image to string with Angular

2019-08-06 11:16发布

问题:

I'm converting an image to a string with the following code. The conversion works when I include some debugger statements. It stops working when I remove them. Here's a link to my github github link What am I missing here?

export class ImageUploaderComponent implements OnInit {
  public context: CanvasRenderingContext2D;
  @ViewChild('mycanvas') mycanvas;
  preview(e: any): void {
    const canvas = this.mycanvas.nativeElement;
    const context = canvas.getContext('2d');
    context.clearRect(0, 0, 300, 300);

    // show image to canvas
     const render = new FileReader();
    render.onload = (event: any) => {
      const img = new Image();
      img.onload = () => {
          canvas.width = img.width;
          canvas.height = img.height;
          context.drawImage(img, 0, 0);
      };
      img.src = event.target.result;
    };
    render.readAsDataURL(e.target.files[0]);
    this.convertBufToStr(render.result);
    localStorage.setItem('imageStore', render.result);
  }
   convertBufToStr(buf): string {
    return String.fromCharCode.apply(null, new Uint16Array(buf));
  }

  convertStrToBuf(str) {
    const buf = new ArrayBuffer(str.length * 2);
    const bufView = new Uint16Array(buf);
    for (let i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  }
  ngOnInit() {}

}

回答1:

The readAsDataURL method is asynchronous. When you call localStorage.setItem('imageStore', render.result), the results are not yet populated. This is why adding debug points solves your issue.

What you can do is to listen the load event of the file reader.

reader.addEventListener("load", function () {
    this.convertBufToStr(render.result);
    localStorage.setItem('imageStore', render.result)
}, false);

You can read more about this API and how it can be used in the MDN article here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL