简体   繁体   English

如何在 React.js 中将 SVG 转换为 PNG 或 JPG/JPEG 文件

[英]How to convert SVG to PNG or JPG/JPEG files in React.js

How can I convert SVG files to png,jpg or jpeg Files in React.js Because I am trying to send my files to server and server only accepts jpg/jpeg or png.我如何在 React.js 中将 SVG 文件转换为 png、jpg 或 jpeg 文件,因为我试图将我的文件发送到服务器,而服务器只接受 jpg/jpeg 或 png。 Any help?有什么帮助吗? I only need files in one of these types.我只需要其中一种类型的文件。 I don't need them in url or blob.我不需要 url 或 blob 中的它们。

The screenshot of file in console控制台文件截图

I searched all over the place.我到处找。 There are some but either the solution is for backend or javascript with dom有一些,但解决方案是用于后端或 javascript with dom

 const [fileImages, setFileImages] = useState<File[]>([]);
  const { state } = useAssetReportContext();

  const charts = state.chartsList.map(({ url, fileName }) => ({
    url,
    fileName,
  }));
  useEffect(() => {
    const fetchImages = () => {
      charts.map(({ url, fileName }) => {
        fetch(url)
          .then((response) => response.blob())
          .then(
            (blob) =>
              new File([blob], `${fileName}`, {
                type: blob.type,
              })
          )
          .then((file) => {
            setFileImages((prev) => [...prev, file]);
          });
      });
    };
    fetchImages();
  }, [state.chartsList.length]);

You can use 'convert-svg-to-png' library.您可以使用“convert-svg-to-png”库。 This is the npm link这是npm链接

Then import it:然后导入它:

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

Then use the following code:然后使用以下代码:

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

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

Hope it works for you:)希望这对你有用:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM