Skip to content

Instantly share code, notes, and snippets.

@seniorjoinu
Created November 9, 2020 23:29
Show Gist options
  • Save seniorjoinu/12444320ca89518d38cc9b3cdd4e1a3f to your computer and use it in GitHub Desktop.
Save seniorjoinu/12444320ca89518d38cc9b3cdd4e1a3f to your computer and use it in GitHub Desktop.
Async SVG to PNG file convert function
// it needs some utilitary canvas to work
export async function transformSvgToPng(canvas: HTMLCanvasElement, svg: File): Promise<File> {
return new Promise((resolve, reject) => {
const ctx = canvas.getContext('2d');
if (!ctx) return reject('Unsupported browser');
const img = new Image;
img.onload = () => {
// this makes result png the same size as the input svg
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
const pngDataUrl = canvas.toDataURL('image/png', 1);
const pngBlob = dataURItoBlob(pngDataUrl);
const pngFileName = svg.name.replace(/svg$/, 'png');
const pngFile = new File([pngBlob], pngFileName, {lastModified: (new Date()).getTime()});
resolve(pngFile);
URL.revokeObjectURL(img.src);
};
img.src = URL.createObjectURL(svg);
});
}
// copy paste from some SO answer
export function dataURItoBlob(dataURI: string): Blob {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
const byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
const mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
const ab = new ArrayBuffer(byteString.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], {type: mimeString});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment