简体   繁体   English

在 Web Worker 中将 SVG 转换为 PNG

[英]Convert SVG to PNG inside Web Worker

I would like to convert an SVG to a PNG inside a Web Worker.我想在 Web Worker 中将 SVG 转换为 PNG。 My problem is, that the DOM is not accessible from within the Worker, so I cannot draw the SVG to a canvas or something like that.我的问题是,无法从 Worker 内部访问 DOM,因此我无法将 SVG 绘制到画布或类似的东西上。

Weeell, you can always manually parse the SVG and build a bitmap from that, but (!) it's a tad more work obviously as you'd have to build a SVG parser as well as a PNG writer, not to mention rasterizing code for lines and two-modes polygon fill incl. Weeell,您始终可以手动解析SVG并从中构建位图,但是(!)显然还有很多工作,因为您必须构建SVG解析器和PNG编写器,更不用说光栅化行代码了和两种模式的多边形填充,包括 anti-aliasing, pattern, matrix, composition, blending and gradient support. 抗锯齿,图案,矩阵,成分,混合和渐变支持。 Could be a nice weekend project though :) 可能是一个不错的周末项目:)

On a more serious note though: you can only do this with the built-in tools using regular context (none-webworker) or optionally set up a server based service. 不过,更重要的一点是:您只能使用带有常规上下文的内置工具(无网络工作人员)来执行此操作,也可以选择设置基于服务器的服务。

You can use thumbo你可以用拇指

import Thumbo, { Transfer } from "thumbo";

Thumbo.init(async () => {
  Thumbo.thumbnail(
    Transfer(await (await fetch("/path/to/img.svg")).arrayBuffer()),
    Thumbo.ImageFormat.Svg,
    20,
    20
  ).then((thumbnailBuffer) => {
    document.getElementById("img1").src = URL.createObjectURL(
      new Blob([thumbnailBuffer])
    );
  });

  Thumbo.thumbnailFromUrl(
    "https://example.com/image.svg",
    Thumbo.ImageFormat.Svg,
    20,
    20
  ).then((thumbnailBuffer) => {
    document.getElementById("img2").src = URL.createObjectURL(
      new Blob([thumbnailBuffer])
    );
  });
});

Under the hood, thumbo uses Rust's tiny_skia & resvg libraries compiled to a Web Assembly module, to render SVG in a web worker and convert it to PNG.在幕后,thumo 使用 Rust 的tiny_skiaresvg库编译为 Web Assembly 模块,在 Web Worker 中渲染 SVG 并将其转换为 PNG。 See thumbo-core , thumbothumbo-core , thumbo

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

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