Convert image to base64 in angular 2

Converting an image in base64 to angular 2, the image is loaded from local. Current am using fileLoadedEvent.target.result. The problem is that when I send this base64 string through REST services in java, it cannot decode it. When I try to use this base64 string with a free online encoder-decoder, there I also do not see the decoded image. I also tried using canvas. I do not get the proper result. It is one thing that the base64 string I get is not correct, do I need to add any package for this? Or in angular 2, is there any percussive way of encoding an image on base64, like it was in the angular 1 package - angular -base64.

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); } } 
+9
source share
5 answers

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)); } 
+32
source

I modified Parth Ghiya's answer a bit, so you can load 1- many images and all of them will be saved in the 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"> 
+3
source

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

cryptojs link - 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);

+1
source

another solution that works for base64 looks like this post fooobar.com/questions/144727 / ...

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 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; } } 
+1
source

I have a response with an HTTP request call for a post method with JSON

1.event parameter comes from an HTML input tag.
2. self.imagesrc is a component variable for storing data and using it in the header file, we need to cast "this" to the variable self and use it in the reader. Download function
3. this.server is the component variable of the calling API service that 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); } }); } 
0
source

Source: https://habr.com/ru/post/1264774/


All Articles