【问题标题】:How to convert base64 dataUrl into image in typescript如何在打字稿中将base64 dataUrl转换为图像
【发布时间】:2019-01-21 11:02:33
【问题描述】:

我正在使用 ng2-image 裁剪器,因为它不采用“src”属性它采用“image”属性。

因此,如果我提供 dataUrl,则图像不会显示在裁剪器中。

我正在使用相机拍摄图像,并从中获取 base64 图像。

想把base64 dataUrl转换成图片,这样就可以在

//component.html 

<div *ngSwitchCase="'camera'">
        <mat-dialog-actions>
            <button mat-raised-button class="capture" (click)="capture()">Take Photo</button>
            <button mat-raised-button mat-dialog-close class="cancel" (click)="closeCamera()" (click)="openDialog()">Cancel</button>
        </mat-dialog-actions>
        <canvas #canvas id="canvas" width="400" height="400"></canvas>
    </div>
    <img-cropper #cropper [image]="data" [settings]="cropperSettings"></img-cropper>


    <span class="result rounded" *ngIf="data">


    <img src="{{data}}" [width]="cropperSettings.croppedWidth"       
      [height]="cropperSettings.croppedHeight"> 

    </span>

从相机中获取图像并在画布中绘制并将其推送到 dataUrl

   // component.ts
    public async capture() {
    var context = this.canvas.nativeElement.getContext("2d").drawImage(this.video.nativeElement, 0, 0, 400, 400);
    await this.captures.push(this.canvas.nativeElement.toDataURL("image/png"));
    this.state = 'photo';
    this.data = this.canvas.nativeElement.toDataURL("image/png");
    localStorage.setItem('webcam', this.data);
}

【问题讨论】:

  • 如果您有一个数据 url,并且希望它显示在 img 元素中,只需将 src 设置为数据 url。您无需将其转换为图像。
  • 我需要在 中设置图像。它不是在获取数据 url,而是在获取图像
  • 即便如此,只需将图像用作 的提要。只需创建一个图像,将 src 设置为数据 URL,然后将该图像用于您的 。无论如何,请检查我的答案,如果您绝对将数据 URL 转换为有用的东西(例如 blob),应该会让您朝着正确的方向前进。

标签: angular typescript html5-canvas webcam-capture


【解决方案1】:

您可以执行以下操作...

首先,将数据 URL 转换为 blob:

convertDataUrlToBlob(dataUrl): Blob {
    const arr = dataUrl.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    const bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);

    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }

    return new Blob([u8arr], {type: mime});
}

接下来,使用 blob 创建一个对象 URL:

const objectURL = URL.createObjectURL(convertDataUrlToBlob(dataUrl));

最后,使用对象 URL 作为图片的src

document.getElementById('myImage').src = objectURL;

如果需要,您还可以将Blob 转换为File

const file = new File([convertDataUrlToBlob(dataUrl)], filename, {type: `image/${extension}`});

【讨论】:

  • 错误:arr[0].match(/:(.*?);/)[1] ==> 对象可能是'null'.ts(2531)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-23
  • 2013-09-24
  • 2018-09-12
  • 2016-03-29
  • 1970-01-01
  • 1970-01-01
  • 2014-11-03
相关资源
最近更新 更多