I am trying to convert an SVG to PNG using Sharp in NodeJs. I have the following code
export const convertSvgToPng = async (svgCode: string) => {
try {
// Convert the SVG code to a PNG buffer
const pngBuffer = await embedImagesInSvg(svgCode);
return pngBuffer;
} catch (error) {
console.error(`Error converting SVG to PNG:`, error);
}
};
// Utility function to download image and convert to Base64
async function fetchImageAsBase64(url: string) {
const response = await axios.get(url, { responseType: 'arraybuffer' });
// Compress the image using sharp
const image = sharp(response.data);
const compressedImageBuffer = await image.png({ compressionLevel: 9 }).toBuffer();
const base64Image = compressedImageBuffer.toString('base64');
const mimeType = response.headers['content-type'];
return `data:${mimeType};base64,${base64Image}`;
}
// Function to modify SVG by embedding multiple base64 images
async function embedImagesInSvg(svgCode: string) {
// let svgContent = fs.readFileSync(svgFilePath, 'utf8');
// Regex to match all xlink:href occurrences
const regex = /xlink:href="([^"]+)"/g;
let match;
const imagePromises = [];
// Collect all image URLs
while ((match = regex.exec(svgCode)) !== null) {
const imageUrl = match[1];
imagePromises.push(fetchImageAsBase64(imageUrl));
}
try {
// Wait for all images to be fetched and converted to base64
const base64Images = await Promise.all(imagePromises);
// Replace each xlink:href with the base64-encoded image
svgCode = svgCode.replace(regex, () => {
const base64Image = base64Images.shift();
return `xlink:href="${base64Image}"`;
});
// Convert the modified SVG to PNG using sharp
return sharp(Buffer.from(svgCode)).png().toBuffer();
} catch (error) {
console.error('Error fetching one or more external images:', error);
}
}
I am using the above code to convert the external image links to base64 before replacing them in the SVG. This is because Sharp doesn’t convert external links to PNG.
The problem is that the base64 strings are too long so Sharp throws the following error
Error converting SVG to PNG: Error: Input buffer has corrupt header: glib: XML parse error: fatal error code=2 (1) in (null):1:10003752: Memory allocation failed : Huge input lookup
I have even tried image compression but that didn’t work
3