使用Angular将图像转换为字符串 [英] convert image to string with Angular

查看:95
本文介绍了使用Angular将图像转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码将图像转换为字符串.当我包含一些调试器语句时,该转换有效.当我删除它们时,它将停止工作. 这是指向我的github的链接 github链接 我在这里想念什么?

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() {}

}

推荐答案

readAsDataURL方法是异步的.当您调用localStorage.setItem('imageStore', render.result)时,结果尚未填充.这就是为什么添加调试点可以解决您的问题的原因.

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);

您可以在此处阅读有关此API的更多信息以及如何在MDN文章中使用它:

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

这篇关于使用Angular将图像转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆