---
title: "convertSvgToPng"
description: "将 SVG 字符串转换为 PNG 格式的 Blob 对象"
seo_title: "convertSvgToPng"
seo_description: "Convert an SVG string into a PNG Blob using a canvas, returning a promise so you can download or upload rasterized image output."
canonical_url: "https://core.mhaibaraai.cn/docs/helpers/file/convert-svg-to-png"
---
# convertSvgToPng

> 将 SVG 字符串转换为 PNG 格式的 Blob 对象

## 用法

`convertSvgToPng` 函数用于将 SVG 字符串转换为 PNG 格式的 Blob 对象。

> \[\!WARNING\]
> 
> 注意
> 
> - 仅在浏览器环境中可用
> - 使用 Canvas API 进行转换
> - 转换失败时会抛出错误

```ts
import { convertSvgToPng } from '@movk/core'

const svgString = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" fill="red"/></svg>'

try {
  const pngBlob = await convertSvgToPng(svgString)
  const url = URL.createObjectURL(pngBlob)

  // 用于下载或显示
  const img = document.createElement('img')
  img.src = url
  document.body.appendChild(img)
}
catch (error) {
  console.error('SVG 转换失败:', error)
}
```

## API

### `convertSvgToPng(svg)`

将 SVG 字符串转换为 PNG 格式的 Blob 对象。

### 参数

**svg** (`string`) *required*: SVG 字符串。

### 返回值

**返回值** (`Promise<Blob>`): PNG 格式的 Blob 对象。

## Changelog

See commit history for [src/helpers/file/convertSvgToPng.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/helpers/file/convertSvgToPng.ts).


## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
