如何在Node.js中将SVG转换为PNG,包括Base64编码的图像?

btxsgosb  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(175)

你好,Stack Overflow社区,
我正在做一个Node.js项目,我需要将SVG文件转换为PNG和JPEG格式。我的SVG文件是独一无二的,因为它们包含编码为base64数据的图像。我尝试使用sharp库进行此操作,但我遇到了base64图像无法正确渲染或在最终PNG输出中丢失的问题。此外,我需要的转换,以保持在最终的PNG图像的高品质。
以下是我的具体要求:

  • 该解决方案应该可以在Node.js环境中实现。
  • 它需要正确处理嵌入base64编码图像的SVG。
  • PNG和JPEG输出的质量应该很高,保持原始SVG的保真度。

我愿意使用其他Node.js库或可以从Node.js应用程序调用的外部工具。任何示例或指针都将非常感谢!
提前感谢您的帮助!
我尝试使用以下方法:

const sharp = require('sharp');
const fs = require('fs');

async function convertSvgToPng(svgFilePath) {
    const outputFilePath = svgFilePath.replace('.svg', '.png');
    const svgBuffer = fs.readFileSync(svgFilePath);

    await sharp(svgBuffer)
        .png()
        .toFile(outputFilePath);

    return outputFilePath;
}

字符串
这段代码似乎不能很好地处理SVG中的base64编码图像,质量也不符合标准。

eqqqjvef

eqqqjvef1#

下面是从SVG和base64创建jpeg文件的示例代码。

async function getQRForGroup(groupuuid, batch) {
  //TODO: fix this for the new host, and the new gallery URL 
  var sURLForGroup = config.BASE_HREF + '/gallery/view/' + groupuuid;
  //var b64String =  async sURLForGroup => await QRCode.toDataURL(sURLForGroup);
  var b64String = null;
  var fontSize = 18;
  var textColor = "#000000";
  var text = "Tachiba";
  var qrCodeUrl = await QRCode.toDataURL(sURLForGroup, { width: 500, margin: 5 });

  // Use sharp to open the generated QR code image
  var b64Str = await sharp(Buffer.from(qrCodeUrl.split(',')[1], 'base64'))
    .jpeg() // You can specify the output format here (e.g., png, webp, etc.)
    .toBuffer()
    .then((inputBuffer) => {
      // Use the buffer to add text to the image using the composite method
      return sharp(inputBuffer)
        .jpeg()
        .composite([
          {
            //viewbox="10 5 100 100"
            input: Buffer.from(`<svg ><text x="0" y="33" font-size="45" fill="${textColor}">${text}</text></svg>`),
            gravity: 'south', // Position of the text on the image
          },
          {
            input: Buffer.from(`
                <svg width="120" height="80">
                <rect width="100%" height="100%" fill="#ffffff"/>
                <text text-anchor="middle" alignment-baseline="central" x="60" y="55" font-size="38" fill="${textColor}">${batch}</text>
                </svg>`),
            gravity: 'center', // Position of the text on the image
          }
        ])
        .toBuffer();
    })
    .then((outputBuffer) => {
      // Convert the final image buffer to a Base64-encoded string
      b64String = outputBuffer.toString('base64');
      return b64String;
    })
    .catch((err) => {
      errorLogger('Error adding text to the QR code image:', err);
    });
  return "data:image/png;base64," + b64Str;
}

字符串
请检查一下。

相关问题