Golang SVG to PNG Conversion: A Simple Example

This guide demonstrates how to convert SVG files to PNG images using the powerful Golang library 'rasterx'. The following code snippet provides a clear and concise example.

package main

import (
    "os"

    "github.com/llgcode/draw2d/draw2dimg"
    "github.com/llgcode/draw2d/draw2dsvg"
    "github.com/llgcode/rasterx"
    "github.com/llgcode/rxsvg"
)

func main() {
    // Parse the image from the SVG file
    img, err := rxsvg.LoadSvgFile('example.svg')
    if err != nil {
        panic(err)
    }

    // Create a canvas with the same dimensions as the image
    canvas := rasterx.NewDenseRaster(img.Bounds().Dx(), img.Bounds().Dy())
    g := rasterx.NewGraphics(canvas)

    // Draw the SVG image
    svg := draw2dsvg.NewGraphicContext(g)
    img.Draw(svg)

    // Save as PNG file
    f, err := os.Create('example.png')
    if err != nil {
        panic(err)
    }
    defer f.Close()
    draw2dimg.SaveToPngFile(f, canvas)
}

This code demonstrates the fundamental steps involved:

  1. Load SVG: Use 'rxsvg.LoadSvgFile' to load the SVG file into memory.
  2. Create Canvas: Initialize a 'rasterx.DenseRaster' canvas matching the image dimensions.
  3. Draw SVG: Utilize 'draw2dsvg.NewGraphicContext' to create a graphics context for drawing the SVG content on the canvas.
  4. Save PNG: Use 'draw2dimg.SaveToPngFile' to save the canvas as a PNG image file.

This example provides a starting point for converting SVG files to PNG in your Golang projects. Explore the 'rasterx' and 'draw2d' libraries for additional functionality and customization options.

Golang SVG to PNG Conversion: A Simple Example

原文地址: https://www.cveoy.top/t/topic/mkdf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录