0

I am new to Angular and facing this issue.

I want to create a custom pipe for convert decimal codes into the base64 image then displaying them in views. I have complete code for this issue but don't know how to use it for the custom pipe.

This is my code:

my-component.ts

this.imgIn = "";
var chars1 = dataParkir.pictstart.data; // array of decimal codes
for (var k = 0; k < chars1.length; k++) {
  var convert = String.fromCharCode(chars1[k]); // convert into base64
  this.imgIn = this.imgIn + convert; 
}

this.base64ImageIn = this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + this.imgIn);

Has anyone else experienced this, please help me?

Daniel
  • 10,641
  • 12
  • 47
  • 85
Lordrauf
  • 99
  • 1
  • 10

2 Answers2

1

I highly suggest you to take a look at the docs, it's really easy to understand and gives you a good amount of information that you might need to create your custom pipe, Here's the link to the official docs: Angular - Pipes

Breno Prata
  • 712
  • 5
  • 10
1

If your snippet of code already does what you want, then moving to a custom pipe is pretty straight forward. You just need to bind your array of decimal and use a pipe that converts it exactly like you do now. Something like:

Pipe:

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
  name: 'base64'
})
export class Base64Pipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer){}

  transform(value: any,){
    let imgIn="";
    for (var k = 0; k < value.length; k++) {
        var convert = String.fromCharCode(value[k]); // convert into base64
        imgIn += convert;
      }
      let base64Url =this.sanitizer.bypassSecurityTrustResourceUrl('data:image/png;base64,' + imgIn);
      return base64Url;
  }
}

And you'd use it like so: [src]="yourDecimalCodeArray | base64"

Here's a Stackblitz to illustrate.


Keep in mind that using this.sanitizer.bypassSecurityTrustResourceUrl mean you have to bind safely (Safe value must use [property]=binding after bypass security with DomSanitizer).

Hope this helps.

Community
  • 1
  • 1
Jojofoulk
  • 2,127
  • 1
  • 7
  • 25