Is there a way to display a base64/array buffer encoded gif to nativescript angular app? I used nativescript-gif but it doesnt work.
Asked
Active
Viewed 662 times
0
-
nativescript-gif doesn't accept base64 string. You will have to convert it to native data and write it to a file, pass the path to the plugin. If you are doing that already, and if it still doesn't work, please share the code you are using for conversion to review. – Manoj Apr 09 '20 at 20:35
-
How can i convert a base64 string to a native data and write it to a file, an example will be very helpful – Aldo Abazi Apr 10 '20 at 08:42
2 Answers
1
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.

Manoj
- 21,753
- 3
- 20
- 41
-
Thanks a lot. Only change i made was file.write to file.writeAsync. write is not a known as a File methode but it worked perfectly.Again thank you – Aldo Abazi Apr 10 '20 at 12:01
0
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.

ruth
- 29,535
- 4
- 30
- 57
-
Thank for your reply but this approach does not work in nativescript. Anyway i menage to convert bytearray in base64 but it does display gif like an image. The plugin i mentioned can display gif but only with a link(internal or external). It does not accept a base64 string as i can see – Aldo Abazi Apr 09 '20 at 15:05