Ani
Ani

Reputation: 75

Convert an Image to byte array in Angular (typescript)

I have a requirement where I need to convert the selected image (a part of a form group) to a byte array which needs to be sent as a part of a post request to the backend.

HTML Component:

<div class="form-group">
                <label>Image</label>
                <input type="file" accept="image/*" class="form-control" formControlName="productImage" onchange="displaySelectedImageFunc(this);">
                <img *ngIf="displaySelectedImage" src="{{selectedImageUrl}}">
                <span class="error-message" *ngIf="itemRegistrationForm.controls.productImage.dirty && itemRegistrationForm.controls.productImage.errors">Select Image of the product</span>
</div>

Upvotes: 2

Views: 19860

Answers (2)

daniel rubambura
daniel rubambura

Reputation: 575

Since you can convert the image to base64 string using reader.readAsDataUR(file) you can extract the byte part with e.target.result.split('base64,')[1] on the reader.onload event like this

const file = document.querySelector('input[type=file]').files[0])
const reader = new FileReader();
reader.onload = (e: any) => {
  const bytes = e.target.result.split('base64,')[1];
};
reader.readAsDataURL(file);

Upvotes: 1

Msk Satheesh
Msk Satheesh

Reputation: 1536

Try Using

function convertDataURIToBinary(dataURI) {
  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(i = 0; i < rawLength; i++) {
    array[i] = raw.charCodeAt(i);
  }
  return array;
}

function upload() {
  const file = document.querySelector('input[type=file]').files[0];
  
  const preview = document.getElementById('preview'); 
  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);
  }
}
<input type="file" id="file" accept="image/*" width="300" height="300" />

<submit onClick="upload()">Upload</submit>

<img id="preview"></img>

Upvotes: 5

Related Questions