ข้ามไปเนื้อหาหลัก

sharp รองรับ SVG input ได้โดยตรงผ่าน librsvg

ไม่ต้องติดตั้ง Inkscape หรือ ImageMagick — sharp แปลง SVG เป็น PNG ได้ทันที

วันนี้เพิ่งค้นพบว่า sharp (image processing library ใน Node.js) รองรับการอ่าน SVG เป็น input ได้โดยตรง ไม่ต้องพึ่ง Inkscape หรือ ImageMagick เลย

const sharp = require('sharp');

const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630">
  <rect width="1200" height="630" fill="#050508"/>
  <text x="80" y="300" fill="#00d4ff" font-size="80">Hello</text>
</svg>`;

await sharp(Buffer.from(svg))
  .png({ quality: 95 })
  .toFile('output.png');

sharp ใช้ librsvg ข้างหลัง ซึ่งติดมากับ libvips ที่ติดตั้งพร้อม npm install sharp อยู่แล้ว

ข้อจำกัดที่ควรรู้: librsvg ไม่รองรับ web fonts จาก @font-face → ต้องใช้ system fonts หรือ embed font data เป็น base64 ใน SVG ถ้าต้องการ custom font ให้ render ถูกต้อง