Angular 如何在typescript中将base64 dataUrl转换为图像
我使用的是ng2图像裁剪器,因为它不是采用“src”属性,而是采用“image”属性 所以,如果我给出dataUrl,图像不会显示在裁剪器中 我使用相机拍摄图像,并从中获得base64图像 要将base64 dataUrl转换为图像,以便在Angular 如何在typescript中将base64 dataUrl转换为图像,angular,typescript,html5-canvas,webcam-capture,Angular,Typescript,Html5 Canvas,Webcam Capture,我使用的是ng2图像裁剪器,因为它不是采用“src”属性,而是采用“image”属性 所以,如果我给出dataUrl,图像不会显示在裁剪器中 我使用相机拍摄图像,并从中获得base64图像 要将base64 dataUrl转换为图像,以便在 //component.html <div *ngSwitchCase="'camera'"> <mat-dialog-actions> <button mat-raised-butt
//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>
您可以执行以下操作 首先,将数据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
转换为文件
:
const file = new File([convertDataUrlToBlob(dataUrl)], filename, {type: `image/${extension}`});
如果您有一个数据url,并且希望它显示在
img
元素中,只需将src设置为数据url。您不需要将其转换为图像。我需要在中设置为图像。它不是在获取数据url,而是在获取图像即使如此,只需将图像用作您对url的提要即可。只需创建一个图像,将src设置为数据URL,并将该图像用于您的应用程序。在任何情况下,请检查我的答案,如果您将数据URL转换为有用的内容,例如blob,那么应该将您设置为正确的方向。
const file = new File([convertDataUrlToBlob(dataUrl)], filename, {type: `image/${extension}`});