Search code examples
angulartypescriptangular-forms

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>

Solution

  • 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>