Skip to content

Commit 3b8b5aa

Browse files
authored
Merge pull request #255 from amazing4u/main
[Security]: Convert base64-data-image-url to blob-url without using fetch!
2 parents d99e3bc + bd799bd commit 3b8b5aa

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

projects/angularx-qrcode/src/lib/angularx-qrcode.component.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,23 @@ export class QRCodeComponent implements OnChanges {
312312
}
313313
}
314314

315+
convertBase64ImageUrlToBlob(base64ImageUrl: string) {
316+
// split into two parts
317+
const parts = base64ImageUrl.split(";base64,")
318+
// hold the content/mime type f.e. image/png
319+
const imageType = parts[0].split(":")[1]
320+
// decode base64 string
321+
const decodedData = atob(parts[1])
322+
// create unit8array of size same as row data length
323+
const uInt8Array = new Uint8Array(decodedData.length)
324+
// insert all character code into uint8array
325+
for (let i = 0; i < decodedData.length; ++i) {
326+
uInt8Array[i] = decodedData.charCodeAt(i)
327+
}
328+
// return blob image after conversion
329+
return new Blob([uInt8Array], { type: imageType })
330+
}
331+
315332
emitQRCodeURL(element: HTMLCanvasElement | HTMLImageElement | SVGSVGElement) {
316333
const className = element.constructor.name
317334
if (className === SVGSVGElement.name) {
@@ -333,17 +350,9 @@ export class QRCodeComponent implements OnChanges {
333350
urlImage = (element as HTMLImageElement).src
334351
}
335352

336-
fetch(urlImage)
337-
.then((urlResponse: Response) => urlResponse.blob())
338-
.then((blob: Blob) => URL.createObjectURL(blob))
339-
.then((url: string) => this.sanitizer.bypassSecurityTrustUrl(url))
340-
.then((urlSanitized: SafeUrl) => {
341-
this.qrCodeURL.emit(urlSanitized)
342-
})
343-
.catch((error) => {
344-
console.error(
345-
"[angularx-qrcode] Error when fetching image/png URL: " + error
346-
)
347-
})
353+
const blobData: Blob = this.convertBase64ImageUrlToBlob(urlImage)
354+
const urlBlob = URL.createObjectURL(blobData)
355+
const urlSanitized = this.sanitizer.bypassSecurityTrustUrl(urlBlob)
356+
this.qrCodeURL.emit(urlSanitized);
348357
}
349358
}

0 commit comments

Comments
 (0)