Converting an image to base64 in angular 2
Asked Answered
V

7

18

Converting an image to base64 in angular 2, image is uploaded from local . Current am using fileLoadedEvent.target.result. The problem is, when I send this base64 string through REST services to java, it is not able to decode it. When i try this base64 string with free online encoder-decoder, there also I cannot see decoded image. I tried using canvas also. Am not getting proper result. One thing is sure the base64 string what am getting is not proper one, do I need to add any package for this ? Or in angular 2 is there any perticular way to encode the image to base64 as it was there in angular 1 - angular-base64-upload package.

Pls find below my sample code

onFileChangeEncodeImageFileAsURL(event:any,imgLogoUpload:any,imageForLogo:any,imageDiv:any)
{
    var filesSelected = imgLogoUpload.files;
    var self = this;
    if (filesSelected.length > 0) {
      var fileToLoad = filesSelected[0]; 

      //Reading Image file, encode and display
       var  reader: FileReader = new FileReader();
       reader.onloadend = function(fileLoadedEvent:any) {

       //SECOND METHO
       var imgSrcData = fileLoadedEvent.target.result; // <--- data: base64 

        var newImage = imageForLogo;
        newImage.src = imgSrcData;
        imageDiv.innerHTML = newImage.outerHTML;

      }
      reader.readAsDataURL(fileToLoad);
    }
}
Vicegerent answered 27/2, 2017 at 10:9 Comment(3)
Do you need to upload the image from input file control to backend?Carrol
ah, ok, I guess it is zone problem... your changes with innerHtml is not how you normally do with angular2.Slaby
try to do the same as in this question: #42483028 when you have a callback onloadend... make it inside of zone, then angular2 will know that view should be updatedSlaby
L
47

Working plunkr for base64 String

https://plnkr.co/edit/PFfebmnqH0eQR9I92v0G?p=preview

  handleFileSelect(evt){
      var files = evt.target.files;
      var file = files[0];

    if (files && file) {
        var reader = new FileReader();

        reader.onload =this._handleReaderLoaded.bind(this);

        reader.readAsBinaryString(file);
    }
  }



  _handleReaderLoaded(readerEvt) {
     var binaryString = readerEvt.target.result;
            this.base64textString= btoa(binaryString);
            console.log(btoa(binaryString));
    }
Lofty answered 27/2, 2017 at 10:29 Comment(3)
This is really useful. I'm curious - I'm implementing this in an array that's taking selected files and iterating over them to encode them. Because there's a slight delay while the encoder works, having the resulting file stored in this.base64textString causes a timing issue. Is it possible to have the encoder take the file reader reference and return the encoded file to the calling function, rather than store it in a local variable?Steinberg
worked for me. Thanks. Do you know how I could reduce the size of the images before sending them to the server?Vanettavang
This worked fine for me as well. Thanks a lotDoykos
H
7

I modified Parth Ghiya answer a bit, so you can upload 1- many images, and they are all stored in an array as base64 encoded strings

base64textString = [];

onUploadChange(evt: any) {
  const file = evt.target.files[0];

  if (file) {
    const reader = new FileReader();

    reader.onload = this.handleReaderLoaded.bind(this);
    reader.readAsBinaryString(file);
  }
}

handleReaderLoaded(e) {
  this.base64textString.push('data:image/png;base64,' + btoa(e.target.result));
}

HTML file

<input type="file" (change)="onUploadChange($event)" accept=".png, .jpg, .jpeg, .pdf" />
<img *ngFor="let item of base64textString"  src={{item}} alt="" id="img">
Hanley answered 11/6, 2018 at 18:49 Comment(0)
S
2

another solution thats works for base64 is something like this post https://mcmap.net/q/86963/-how-to-convert-file-to-base64-in-javascript

in my case, i did

getImagem(readerEvt, midia){
    //console.log('change no input file', readerEvt);
    let file = readerEvt.target.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        //console.log('base64 do arquivo',reader.result);
        midia.binario = btoa(reader.result);
        //console.log('base64 do arquivo codificado',midia.binario);
    };
    reader.onerror = function (error) {
        console.log('Erro ao ler a imagem : ', error);
    };
}

and html component

<input type="file" class="form-control"  (change)="getImagem($event, imagem)">

<img class="img-responsive"  src="{{imagem.binario | decode64 }}" alt="imagem..." style="width: 200px;"/>

to display the image, i created the pipe decode64

@Pipe({
  name: 'decode64'
})
export class Decode64Pipe implements PipeTransform {
  transform(value: any, args?: any): any {
    let a = '';
    if(value){
       a = atob(value);
    }
    return a;
  }
}
Supernational answered 6/7, 2017 at 2:24 Comment(0)
E
1

Have you tried using btoa or Crypto.js to encode the image to base64 ?

link to cryptojs - https://code.google.com/archive/p/crypto-js/

var imgSrcData = window.btoa(fileLoadedEvent.target.result);

or var imgSrcData = CryptoJS.enc.Base64.stringify(fileLoadedEvent.target.result);

Eichhorn answered 27/2, 2017 at 10:30 Comment(1)
I tried with btoa and crypto also. But same string it was giving.Vicegerent
D
1

Here is the same code from Parth Ghiya but written in ES6/TypeScript format

picture: string;
handleFileSelect(evt){
    const file = evt.target.files[0];
    if (!file) {
        return false;
    }
    const reader = new FileReader();
    
    reader.onload = () => {
        this.picture = reader.result as string;
    };

    console.log(btoa(this.picture));
}
Diplomate answered 17/7, 2020 at 21:6 Comment(0)
R
0

I have a come up with an answer with calling the HTTP request for post method with a json

1.event param is coming from the HTML input tag.
2. self.imagesrc is a component variable to store the data and to use that in the header file we need to cast the "this" to a self variable and use it in the reader. Onload function
3. this.server is the API calling service component variable I used in this component

UploadImages(event) {
    var file = event.target.files[0];
    var reader = new FileReader();
    reader.readAsDataURL(file);
    var self = this;
    reader.onload = function() {
      self.imageSrc = reader.result.toString();
    };

    var image_data = {
      authentication_token: this.UD.getAuth_key ,
      fileToUpload: this.imageSrc,
      attachable_type: "Photo"
    };

    this.server.photo_Upload(image_data).subscribe(response => {
      if (response["success"]) {
        console.log(response);
      } else {
        console.log(response);
      }
    });
  }
Rhetoric answered 22/5, 2019 at 7:18 Comment(0)
S
0

Please consider using this package: image-to-base64

Generate a image to base64, you can make this using a path or url.

Or this accepted answer

Surat answered 23/5, 2020 at 13:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.