svg文本转为对应图片的base64编码

转换脚本(node)

npm init -y
npm install express sharp body-parser

const express = require('express');
const bodyParser = require('body-parser');
const sharp = require('sharp');

const app = express();
const port = 5000;

// 配置body-parser以接受JSON格式的数据
app.use(bodyParser.json());

app.post('/convert-svg', async (req, res) => {
    
    
  try {
    
    
    // 从请求体中获取svg_content
    const svg = req.body.svg_content;

    const pngBuffer = await sharp(Buffer.from(svg)).toFormat('png').toBuffer();
    const base64PNG = pngBuffer.toString('base64');

    res.send(base64PNG);
  } catch (error) {
    
    
    console.error('Error converting SVG to PNG:', error);
    res.status(500).send('An error occurred during the conversion process.');
  }
});

app.listen(port, () => {
    
    
  console.log(`Server running at http://localhost:${
      
      port}`);
});

python测试脚本

import requests
import json

# SVG文件的路径
svg_file_path = 'svgfile.svg'

# Node.js服务器的URL
url = 'http://localhost:5000/convert-svg'

# 从文件中读取SVG内容
with open(svg_file_path, 'r') as file:
    svg_content = file.read()

# 构造JSON数据
data = {
    
    "svg_content": svg_content}

# 发送POST请求
response = requests.post(url, json=data)

# 检查响应
if response.status_code == 200:
    # 打印Base64编码的PNG图像
    print("Base64 PNG:", response.text)
else:
    print("Error:", response.status_code, response.text)

猜你喜欢

转载自blog.csdn.net/dzdzdzd12347/article/details/135051344