Skip to content

Instantly share code, notes, and snippets.

@balvinder294
Last active June 10, 2020 07:51
Show Gist options
  • Save balvinder294/eaee6c61021862c24550bcc7244c7cbe to your computer and use it in GitHub Desktop.
Save balvinder294/eaee6c61021862c24550bcc7244c7cbe to your computer and use it in GitHub Desktop.
Method to create a Blob file from Base64Url - Tekraze
/**Method that will create Blob and show in new window */
createBlobImageFileAndShow(): void {
this.dataURItoBlob(this.base64TrimmedURL).subscribe((blob: Blob) => {
const imageBlob: Blob = blob;
const imageName: string = this.generateName();
const imageFile: File = new File([imageBlob], imageName, {
type: "image/jpeg"
});
this.generatedImage = window.URL.createObjectURL(imageFile);
window.open(this.generatedImage);
});
}
/* Method to convert Base64Data Url as Image Blob */
dataURItoBlob(dataURI: string): Observable<Blob> {
return Observable.create((observer: Observer<Blob>) => {
const byteString: string = window.atob(dataURI);
const arrayBuffer: ArrayBuffer = new ArrayBuffer(byteString.length);
const int8Array: Uint8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < byteString.length; i++) {
int8Array[i] = byteString.charCodeAt(i);
}
const blob = new Blob([int8Array], { type: "image/jpeg" });
observer.next(blob);
observer.complete();
});
}
/**Method to Generate a Name for the Image */
generateName(): string {
const date: number = new Date().valueOf();
let text: string = "";
const possibleText: string =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (let i = 0; i < 5; i++) {
text += possibleText.charAt(
Math.floor(Math.random() * possibleText.length)
);
}
// Replace extension according to your media type like this
return date + "." + text + ".jpeg";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment