I used this link for Convert an Image to byte array in Angular
Convert an Image to byte array in Angular (typescript)
but src not bind to image for preview my typescript code is :
upload() : void {
const file = (document.querySelector('input[type=file]') as HTMLInputElement).files![0];
const preview = document.getElementById('preview') as HTMLImageElement;
const reader = new FileReader();
let byteArray;
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
**preview.src != reader.result;**
byteArray = convertDataURIToBinary(reader.result);
console.log('byte array', byteArray);
}, false);
if (file) {
reader!.readAsDataURL(file);
}
}
}
function convertDataURIToBinary(dataURI:any) {
var base64Index = dataURI.indexOf(';base64,') ';base64,'.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for(let i = 0; i < rawLength; i ) {
array[i] = raw.charCodeAt(i);
}
return array;
}
and my html is
<input type="file" id="file" accept="image/*" width="300" height="300" />
<button (click)="upload()">Upload</button>
<img id="preview">
My problem is this line that src is empty and the image not be shown
Thank you
CodePudding user response:
You shouldn't "target" the element from your typescript but instead use a data binding approach which is a go-to way in Angular.
In your HTML:
<img src="{{previewImage}}" *ngIf="previewImage">
In your typescript update the following snippet:
reader.addEventListener("loadend", function () {
// convert image file to base64 string
console.log('base64', reader.result);
**preview.src != reader.result;**
...
into this:
reader.addEventListener("loadend", () => {
// convert image file to base64 string
console.log('base64', reader.result);
this.previewImage = reader.result;
...
CodePudding user response:
Please save the reader result into a variable and use the same as the source to an img tag in HTML
TS File :
binaryImage : any;
...
this.binaryImage = reader.result;
...
HTML File:
<img src="{{binaryImage}}">
or
<div style="background-image: url({{binaryImage}});">