Aldo Abazi
Aldo Abazi

Reputation: 385

Display base64 encoded gif in nativescript angular app

Is there a way to display a base64/array buffer encoded gif to nativescript angular app? I used nativescript-gif but it doesnt work.

Upvotes: 0

Views: 738

Answers (2)

Manoj
Manoj

Reputation: 21908

You can use the native APIs to write your base64 string to a file, then pass the file path to GIF plugin.

    const base64Data = "Your_Base64_String";

    const file = File.fromPath("ValidFilePath...");
    let nativeData;

    if (isIOS) {
        nativeData = NSData.alloc().initWithBase64EncodedStringOptions(base64Data, 0);
    }

    if (isAndroid) {
        nativeData = android.util.Base64.decode(base64Data, android.util.Base64.NO_WRAP);
    }

    file.writeSync(nativeData);

I did test the code on Playground, FYI since Playground do not support GIF plugin so I used Image component for testing. Also ensure I'm passing a valid string, I download a random GIF from internet and convert it to base64 string.

Upvotes: 1

Barremian
Barremian

Reputation: 31125

You could try to convert the array buffer to base64 manually before displaying the gif. Try the following

Image service

import { pipe } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class ImageService() {
  private arrayBufferToBase64(buffer: any) {
    let binary = '';
    const bytes = new Uint8Array(buffer);
    const len = bytes.byteLength;
    for (let i = 0; i < len; i++) {
      binary += String.fromCharCode(bytes[i]);
    }
    return window.btoa(binary);
  }

  public getImage(id: number): observable<any> {
    return this.http.get(BASE_URL + '/' + id).pipe(map(buffer => this.arrayBufferToBase64(buffer)));
  }
}

Controller

import { DomSanitizer } from '@angular/platform-browser';

export class AppComponent implements OnInit, OnDestroy {
  imageSource: any;

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {
    this.imageService.getImage(1).subscribe(
      base64 => {
        this.imageSource = this.sanitizer.bypassSecurityTrustResourceUrl(`data:image/gif;base64, ${base64}`);
      },
      error => {
        // handle error
      }
    );
  }
}

Template

<img [src]="imageSource" alt="Image Source">

The function arrayBufferToBase64() is sourced from here.

Upvotes: 0

Related Questions