如何在 React 中将 SVG 转换为 PNG?

问题描述 投票:0回答:4

我尝试使用这个库:https://www.npmjs.com/package/convert-svg-to-png

但是出现错误:

import { convert } from 'convert-svg-to-png'

    useEffect(() => {
        let png = convert('/iStock-1188768310.svg')
        console.log(png)
    })
Error: Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/tar-fs/index.js
./node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserFetcher.js
./node_modules/puppeteer/lib/cjs/puppeteer/node/Puppeteer.js
./node_modules/puppeteer/lib/cjs/puppeteer/initialize-node.js

我做错了什么,或者这是更“标准”的方法吗?我的目标是使用 az an

og:image
图像。我听说 SVG 不能使用,这就是为什么我尝试转换为 PNG。


我也尝试了这个包:https://github.com/canvg/canvg像这样:

const canvas = document.querySelector('canvas')
        const ctx = canvas.getContext('2d')

        v = await Canvg.from(ctx, './svgs/1.svg')

        // Start SVG rendering with animations and mouse handling.
        v.start()

但它也会引发错误:

TypeError: Cannot read properties of null (reading 'getContext')
  24 |  let cv = async () => {
  25 |      const canvas = document.querySelector('canvas')
> 26 |      const ctx = canvas.getContext('2d')
     |                        ^
  27 | 
  28 |      v = await Canvg.from(ctx, './sv
reactjs svg png
4个回答
2
投票

根据库的npm页面,您需要导入的函数是convertFile而不是convert

const { convertFile}  = require('convert-svg-to-png');

以下代码应该可以工作:

(async() => {
  const inputFilePath = '/path/to/my-image.svg';
  const outputFilePath = await convertFile(inputFilePath);

  console.log(outputFilePath);
  //=> "/path/to/my-image.png"
})();

0
投票

标题为“使用 headless Chromium 将 SVG 转换为 PNG 的 Node.js 包”。您只能在 Nodejs 中使用它,而不能在客户端 JavaScript 中使用它。如果您想在浏览器中执行此操作,您可能需要检查此答案:在浏览器中将 SVG 转换为图像(JPEG、PNG 等)


0
投票

这里有一个(客户端)示例,说明如何使用 fetch() 加载 SVG 文档(如果 SVG 尚未在 DOM 中),将其转换为 File 对象,在画布上绘制并导出为 PNG。

var svgcontainer, svg, canvas, ctx, output;

document.addEventListener('DOMContentLoaded', e => {
  svgcontainer = document.getElementById('svgcontainer');
  canvas = document.getElementById('canvas');
  output = document.getElementById('output');
  ctx = canvas.getContext('2d');
  fetch('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8Y2lyY2xlIGN4PSI1MCIgY3k9IjUwIiByPSI1MCIgZmlsbD0ib3JhbmdlIiAvPgo8L3N2Zz4KCgo=').then(res => res.text()).then(text => {
    let parser = new DOMParser();
    let svgdoc = parser.parseFromString(text, "application/xml");
    canvas.width = svgdoc.rootElement.getAttribute('width');
    canvas.height = svgdoc.rootElement.getAttribute('height');

    // append SVG to DOM
    svgcontainer.innerHTML = svgdoc.rootElement.outerHTML;
    svg = svgcontainer.querySelector('svg');

    // create a File object
    let file = new File([svgdoc.rootElement.outerHTML], 'svg.svg', {
      type: "image/svg+xml"
    });
    // and a reader
    let reader = new FileReader();

    reader.addEventListener('load', e => {
      /* create a new image assign the result of the filereader
      to the image src */
      let img = new Image();
      // wait for it to got load
      img.addEventListener('load', e => {
        // update canvas with new image
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.drawImage(e.target, 0, 0);
        // create PNG image based on canvas
        let img = new Image();
        img.src = canvas.toDataURL("image/png");
        output.append(img);
      });
      img.src = e.target.result;
    });
    // read the file as a data URL
    reader.readAsDataURL(file);
  });
});
<div style="display:flex">
  SVG:
  <div id="svgcontainer"></div>
  Canvas: <canvas id="canvas" width="200" height="200"></canvas>
</div>
<p>Exported PNG:</p>
<div id="output"></div>


0
投票

这是您在 React Native 中使用的一些函数,用于将 SVG 转换为 PNG 基本上,首先我们将 SVG 文件转换为 Base64 数据,然后将其转换为 PNG 文件并存储在本地存储中,您可以在 pngDataUri 中看到文件位置

//这些函数用于将SVG图像转换为PNG图像

const convertSvgToImage = async (svgContent) => {
    try {
      const pngDataUri = await convertSvgToPng(svgContent, 400, 400);
      // console.log(pngDataUri.toDataURL());
      console.log('PNG Data URL:', pngDataUri)
      const fileExists = await FileSystem.getInfoAsync(pngDataUri);
      console.log(fileExists);
      if (fileExists.exists) {
        // The file exists, you can read or manipulate it here
        // For example, you can copy it to another location
        console.log(FileSystem.documentDirectory)
        const base64Data = await FileSystem.readAsStringAsync(fileExists.uri, {
          encoding: 'base64',
        });
        const dataUri = `data:image/png;base64,${base64Data}`;
        // console.log("Data URI is "+dataUri);
        setbase64(dataUri);
        return dataUri;
      };
    } catch (error) {
      console.error('Conversion failed:', error);
    }
  };
  const captureView = async (view, width, height) => {3
    return new Promise((resolve, reject) => {
      ref.current.capture().then(uri => {
        resolve(uri);
      }).catch(error => {
        reject(error);
      });
    });
  };
  const convertSvgToPng = async (svgXml, width, height) => {
    return new Promise((resolve, reject) => {
      try {
        const svgDataUri = `data:image/svg+xml;base64,${btoa(svgXml)}`;
        console.log("svgData is = ",svgDataUri);
        const img = Image.resolveAssetSource({ uri: svgDataUri });
        img.width = width;
        img.height = height;
  
        const result = captureView(img, width, height);
        
        resolve(result);
      } catch (error) {
        reject(error);
        console.log("errror in cathc")
      }
    });
  };

使用 ViewShot 获取 SVG Img 的引用

<ViewShot ref={ref}>
  <Svg width="100%" height="100%">
     {renderPaths()}
     {currentPath.length > 1 && (
       <Path
          d={`M${currentPath.map(p => `${p.x},${p.y}`).join(' L')}`}
          fill="none"
          stroke="black"
          strokeWidth={2}
        />
       )}
     </Svg>
 </ViewShot>
© www.soinside.com 2019 - 2024. All rights reserved.