### Render SVG to PNG in Go Source: https://context7.com/srwiley/oksvg/llms.txt Full workflow for loading an SVG file, scaling it to a target size, and saving the result as a PNG image. ```go package main import ( "bufio" "image" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { // Load SVG icon icon, err := oksvg.ReadIcon("testdata/landscapeIcons/mountains.svg", oksvg.WarnErrorMode) if err != nil { panic(err) } // Target size (can be different from original viewBox) targetW, targetH := 256, 256 // Create RGBA image buffer img := image.NewRGBA(image.Rect(0, 0, targetW, targetH)) // Create scanner (converts paths to pixels) scanner := rasterx.NewScannerGV(targetW, targetH, img, img.Bounds()) // Create dasher (handles stroking with dashes, caps, joins) raster := rasterx.NewDasher(targetW, targetH, scanner) // Scale SVG to fit target dimensions icon.SetTarget(0, 0, float64(targetW), float64(targetH)) // Render at full opacity icon.Draw(raster, 1.0) // Save to PNG file f, err := os.Create("mountains_256.png") if err != nil { panic(err) } defer f.Close() w := bufio.NewWriter(f) if err := png.Encode(w, img); err != nil { panic(err) } w.Flush() } ``` -------------------------------- ### Load and Render SVG from File Source: https://context7.com/srwiley/oksvg/llms.txt Reads an SVG file from the filesystem and renders it to a PNG image using the rasterx package. ```go package main import ( "fmt" "image" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { // Load an SVG icon from file with warning mode enabled icon, err := oksvg.ReadIcon("icon.svg", oksvg.WarnErrorMode) if err != nil { fmt.Printf("Error loading SVG: %v\n", err) return } // Get dimensions from the SVG viewBox w, h := int(icon.ViewBox.W), int(icon.ViewBox.H) fmt.Printf("SVG dimensions: %dx%d\n", w, h) // Create output image and rasterizer img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) // Draw the icon at full opacity icon.Draw(raster, 1.0) // Save to PNG f, _ := os.Create("output.png") defer f.Close() png.Encode(f, img) // Output: SVG dimensions: 512x512 } ``` -------------------------------- ### Configure SVG Error Handling in Go Source: https://context7.com/srwiley/oksvg/llms.txt Demonstrates how to use IgnoreErrorMode, WarnErrorMode, and StrictErrorMode to control parser behavior when encountering unsupported elements. ```go package main import ( "fmt" "strings" "github.com/srwiley/oksvg" ) func main() { // SVG with an unsupported element (text) svgWithUnsupported := ` Hello ` // IgnoreErrorMode: silently skips unsupported elements icon1, err := oksvg.ReadIconStream( strings.NewReader(svgWithUnsupported), oksvg.IgnoreErrorMode, ) fmt.Printf("IgnoreMode: err=%v, paths=%d\n", err, len(icon1.SVGPaths)) // WarnErrorMode: logs warning but continues parsing icon2, err := oksvg.ReadIconStream( strings.NewReader(svgWithUnsupported), oksvg.WarnErrorMode, ) fmt.Printf("WarnMode: err=%v, paths=%d\n", err, len(icon2.SVGPaths)) // StrictErrorMode: returns error on unsupported elements icon3, err := oksvg.ReadIconStream( strings.NewReader(svgWithUnsupported), oksvg.StrictErrorMode, ) if err != nil { fmt.Printf("StrictMode: err=%v\n", err) } else { fmt.Printf("StrictMode: paths=%d\n", len(icon3.SVGPaths)) } // Output: // IgnoreMode: err=, paths=1 // WarnMode: err=, paths=1 // StrictMode: err=Cannot process svg element text } ``` -------------------------------- ### Set Target for SVG Scaling and Positioning Source: https://context7.com/srwiley/oksvg/llms.txt Demonstrates drawing an SVG icon at multiple sizes and positions on a larger canvas by using the SetTarget method. Outputs 'multi_size.png'. ```go package main import ( "image" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { icon, _ := oksvg.ReadIcon("icon.svg", oksvg.IgnoreErrorMode) // Create a larger canvas canvasW, canvasH := 400, 300 img := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH)) scanner := rasterx.NewScannerGV(canvasW, canvasH, img, img.Bounds()) raster := rasterx.NewDasher(canvasW, canvasH, scanner) // Draw icon at multiple sizes and positions // Top-left: small icon (50x50) icon.SetTarget(10, 10, 50, 50) icon.Draw(raster, 1.0) // Center: medium icon (100x100) icon.SetTarget(150, 100, 100, 100) icon.Draw(raster, 1.0) // Bottom-right: stretched icon (100x50) icon.SetTarget(290, 240, 100, 50) icon.Draw(raster, 1.0) f, _ := os.Create("multi_size.png") defer f.Close() png.Encode(f, img) } ``` -------------------------------- ### Draw SVG Icon with Opacity and Transform Source: https://context7.com/srwiley/oksvg/llms.txt Renders an SVG icon at full opacity on the left and at 50% opacity with a translation transform on the right. Requires an 'icon.svg' file and outputs 'opacity_comparison.png'. ```go package main import ( "image" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { icon, _ := oksvg.ReadIcon("icon.svg", oksvg.IgnoreErrorMode) w, h := int(icon.ViewBox.W), int(icon.ViewBox.H) img := image.NewRGBA(image.Rect(0, 0, w*2, h)) scanner := rasterx.NewScannerGV(w*2, h, img, img.Bounds()) raster := rasterx.NewDasher(w*2, h, scanner) // Draw at full opacity on the left icon.Draw(raster, 1.0) // Draw at 50% opacity on the right with transform icon.Transform = rasterx.Identity.Translate(float64(w), 0) icon.Draw(raster, 0.5) f, _ := os.Create("opacity_comparison.png") defer f.Close() png.Encode(f, img) } ``` -------------------------------- ### ReadIcon Source: https://context7.com/srwiley/oksvg/llms.txt Reads an SVG file from the filesystem and parses it into an SvgIcon structure. ```APIDOC ## ReadIcon ### Description Reads an SVG file from the filesystem and parses it into an SvgIcon structure. This is the primary entry point for loading SVG files. ### Parameters #### Path Parameters - **path** (string) - Required - The filesystem path to the SVG file. - **mode** (ErrorMode) - Required - Controls how the parser handles unsupported SVG elements (IgnoreErrorMode, WarnErrorMode, or StrictErrorMode). ### Response - **icon** (*SvgIcon) - The parsed SVG icon structure. - **err** (error) - Error object if parsing fails. ``` -------------------------------- ### Compile SVG Path Data Source: https://context7.com/srwiley/oksvg/llms.txt Compiles a given SVG path data string into rasterx path commands using PathCursor. Supports all standard SVG path commands. Renders a star shape to 'star.png'. ```go package main import ( "fmt" "image" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { // Create a path cursor to compile SVG path data cursor := &oksvg.PathCursor{} // SVG path data for a star shape pathData := `M 50,5 L 61,40 L 98,40 L 68,62 L 79,97 L 50,75 L 21,97 L 32,62 L 2,40 L 39,40 Z` err := cursor.CompilePath(pathData) if err != nil { fmt.Printf("Error compiling path: %v\n", err) return } // Create an icon manually with the compiled path icon := oksvg.SvgIcon{} icon.ViewBox.W = 100 icon.ViewBox.H = 100 // Add the path with default style (black fill) icon.SVGPaths = append(icon.SVGPaths, oksvg.SvgPath{ PathStyle: oksvg.DefaultStyle, Path: cursor.Path, }) // Render the star w, h := 200, 200 img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) icon.SetTarget(0, 0, float64(w), float64(h)) icon.Draw(raster, 1.0) f, _ := os.Create("star.png") defer f.Close() png.Encode(f, img) fmt.Println("Star rendered from path data") // Output: Star rendered from path data } ``` -------------------------------- ### Parse and Render SVG from Stream Source: https://context7.com/srwiley/oksvg/llms.txt Parses SVG content from an io.Reader, suitable for network responses or embedded resources. ```go package main import ( "bytes" "fmt" "image" "strings" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { // SVG content as a string (could come from HTTP response, database, etc.) svgContent := ` ` // Create reader from string reader := strings.NewReader(svgContent) // Parse the SVG stream icon, err := oksvg.ReadIconStream(reader, oksvg.StrictErrorMode) if err != nil { fmt.Printf("Error parsing SVG: %v\n", err) return } // Render to image w, h := int(icon.ViewBox.W), int(icon.ViewBox.H) img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) icon.Draw(raster, 1.0) fmt.Printf("Rendered SVG with %d paths\n", len(icon.SVGPaths)) // Output: Rendered SVG with 2 paths } ``` -------------------------------- ### SvgIcon.Draw Source: https://context7.com/srwiley/oksvg/llms.txt Renders a parsed SVG icon to a rasterx Dasher at a specified opacity. The opacity value ranges from 0.0 (fully transparent) to 1.0 (fully opaque). ```APIDOC ## SvgIcon.Draw ### Description Renders the parsed SVG icon into a rasterx Dasher at the specified opacity. The opacity parameter (0.0 to 1.0) affects the overall transparency of the rendered output. ### Method (Implicitly called via Draw method on SvgIcon object) ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within a Go program icon, _ := oksvg.ReadIcon("icon.svg", oksvg.IgnoreErrorMode) w, h := int(icon.ViewBox.W), int(icon.ViewBox.H) img := image.NewRGBA(image.Rect(0, 0, w*2, h)) scanner := rasterx.NewScannerGV(w*2, h, img, img.Bounds()) raster := rasterx.NewDasher(w*2, h, scanner) // Draw at full opacity on the left icon.Draw(raster, 1.0) // Draw at 50% opacity on the right with transform icon.Transform = rasterx.Identity.Translate(float64(w), 0) icon.Draw(raster, 0.5) f, _ := os.Create("opacity_comparison.png") defer f.Close() png.Encode(f, img) ``` ### Response #### Success Response (200) N/A (This function modifies an image buffer in memory) #### Response Example N/A ``` -------------------------------- ### PathCursor.CompilePath Source: https://context7.com/srwiley/oksvg/llms.txt Parses an SVG path data string (the 'd' attribute) into rasterx path commands. It supports all standard SVG path commands including moveto, lineto, horizontal, vertical, cubic bezier, smooth cubic, quadratic bezier, smooth quadratic, arc, and close path. ```APIDOC ## PathCursor.CompilePath ### Description Parses an SVG path data string (the 'd' attribute) into rasterx path commands. Supports all standard SVG path commands: M/m (moveto), L/l (lineto), H/h (horizontal), V/v (vertical), C/c (cubic bezier), S/s (smooth cubic), Q/q (quadratic bezier), T/t (smooth quadratic), A/a (arc), and Z/z (close path). ### Method (Implicitly called via CompilePath method on PathCursor object) ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within a Go program cursor := &oksvg.PathCursor{} // SVG path data for a star shape pathData := `M 50,5 L 61,40 L 98,40 L 68,62 L 79,97 L 50,75 L 21,97 L 32,62 L 2,40 L 39,40 Z` err := cursor.CompilePath(pathData) if err != nil { fmt.Printf("Error compiling path: %v\n", err) return } // Create an icon manually with the compiled path icon := oksvg.SvgIcon{} icon.ViewBox.W = 100 icon.ViewBox.H = 100 // Add the path with default style (black fill) icon.SVGPaths = append(icon.SVGPaths, oksvg.SvgPath{ PathStyle: oksvg.DefaultStyle, Path: cursor.Path, }) // Render the star w, h := 200, 200 img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) icon.SetTarget(0, 0, float64(w), float64(h)) icon.Draw(raster, 1.0) f, _ := os.Create("star.png") defer f.Close() png.Encode(f, img) fmt.Println("Star rendered from path data") ``` ### Response #### Success Response (200) N/A (This function returns an error or modifies the PathCursor's internal Path field) #### Response Example N/A ``` -------------------------------- ### Parse SVG Colors in Go Source: https://context7.com/srwiley/oksvg/llms.txt Parses various SVG color formats including hex, rgb, hsl, and named colors. Returns nil for the 'none' keyword. ```go package main import ( "fmt" "image/color" "github.com/srwiley/oksvg" ) func main() { // Parse different color formats colors := []string{ "#FF5722", // 6-digit hex "#F00", // 3-digit hex "rgb(66, 133, 244)", // RGB function "hsl(198, 47%, 65%)", // HSL function "dodgerblue", // Named color "none", // No color (returns nil) } for _, colorStr := range colors { c, err := oksvg.ParseSVGColor(colorStr) if err != nil { fmt.Printf("Error parsing '%s': %v\n", colorStr, err) continue } if c == nil { fmt.Printf("'%s' -> none (transparent)\n", colorStr) } else { rgba := c.(color.NRGBA) fmt.Printf("'%s' -> RGBA(%d, %d, %d, %d)\n", colorStr, rgba.R, rgba.G, rgba.B, rgba.A) } } // Output: // '#FF5722' -> RGBA(255, 87, 34, 255) // '#F00' -> RGBA(255, 0, 0, 255) // 'rgb(66, 133, 244)' -> RGBA(66, 133, 244, 255) // 'hsl(198, 47%, 65%)' -> RGBA(124, 183, 208, 255) // 'dodgerblue' -> RGBA(30, 144, 255, 255) // 'none' -> none (transparent) } ``` -------------------------------- ### Modify SVG Path Colors in Go Source: https://context7.com/srwiley/oksvg/llms.txt Updates fill and stroke colors of individual SVG paths after loading. Requires rasterx for rendering the modified icon. ```go package main import ( "image" "image/color" "image/png" "os" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { icon, _ := oksvg.ReadIcon("icon.svg", oksvg.IgnoreErrorMode) // Modify colors of individual paths for i := range icon.SVGPaths { // Get current colors fillColor := icon.SVGPaths[i].GetFillColor() lineColor := icon.SVGPaths[i].GetLineColor() // Set new colors - make fills blue and strokes red if fillColor != nil { icon.SVGPaths[i].SetFillColor(color.NRGBA{R: 0, G: 100, B: 200, A: 255}) } if lineColor != nil { icon.SVGPaths[i].SetLineColor(color.NRGBA{R: 200, G: 50, B: 50, A: 255}) } } // Render with modified colors w, h := int(icon.ViewBox.W), int(icon.ViewBox.H) img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) icon.Draw(raster, 1.0) f, _ := os.Create("recolored.png") defer f.Close() png.Encode(f, img) } ``` -------------------------------- ### ReadIconStream Source: https://context7.com/srwiley/oksvg/llms.txt Reads and parses an SVG from an io.Reader stream. ```APIDOC ## ReadIconStream ### Description Reads and parses an SVG from an io.Reader stream instead of a file path. Useful for network responses or embedded resources. ### Parameters #### Parameters - **reader** (io.Reader) - Required - The input stream containing SVG data. - **mode** (ErrorMode) - Required - Controls how the parser handles unsupported SVG elements. ### Response - **icon** (*SvgIcon) - The parsed SVG icon structure. - **err** (error) - Error object if parsing fails. ``` -------------------------------- ### Theme SVG with CurrentColor Replacement Source: https://context7.com/srwiley/oksvg/llms.txt Replaces CSS currentColor values in an SVG with a specific color during parsing for dynamic theming. ```go package main import ( "fmt" "image" "strings" "github.com/srwiley/oksvg" "github.com/srwiley/rasterx" ) func main() { // SVG using currentColor for theming svgContent := ` ` reader := strings.NewReader(svgContent) // Replace currentColor with a specific color (hex, rgb, or named color) icon, err := oksvg.ReadReplacingCurrentColor(reader, "#FF5722", oksvg.IgnoreErrorMode) if err != nil { fmt.Printf("Error: %v\n", err) return } // Render the themed icon w, h := 48, 48 img := image.NewRGBA(image.Rect(0, 0, w, h)) scanner := rasterx.NewScannerGV(w, h, img, img.Bounds()) raster := rasterx.NewDasher(w, h, scanner) icon.SetTarget(0, 0, float64(w), float64(h)) icon.Draw(raster, 1.0) fmt.Println("Icon themed with color #FF5722") // Output: Icon themed with color #FF5722 } ``` -------------------------------- ### SvgIcon.SetTarget Source: https://context7.com/srwiley/oksvg/llms.txt Configures the transformation matrix to scale and position the SVG within a target rectangle. This is crucial for rendering SVGs at sizes different from their native viewBox dimensions. ```APIDOC ## SvgIcon.SetTarget ### Description Configures the transformation matrix to scale and position the SVG within a target rectangle. This is essential for rendering SVGs at different sizes than their native viewBox dimensions. ### Method (Implicitly called via SetTarget method on SvgIcon object) ### Endpoint N/A (This is a library function, not an API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage within a Go program icon, _ := oksvg.ReadIcon("icon.svg", oksvg.IgnoreErrorMode) // Create a larger canvas canvasW, canvasH := 400, 300 img := image.NewRGBA(image.Rect(0, 0, canvasW, canvasH)) scanner := rasterx.NewScannerGV(canvasW, canvasH, img, img.Bounds()) raster := rasterx.NewDasher(canvasW, canvasH, scanner) // Draw icon at multiple sizes and positions // Top-left: small icon (50x50) icon.SetTarget(10, 10, 50, 50) icon.Draw(raster, 1.0) // Center: medium icon (100x100) icon.SetTarget(150, 100, 100, 100) icon.Draw(raster, 1.0) // Bottom-right: stretched icon (100x50) icon.SetTarget(290, 240, 100, 50) icon.Draw(raster, 1.0) f, _ := os.Create("multi_size.png") defer f.Close() png.Encode(f, img) ``` ### Response #### Success Response (200) N/A (This function modifies an image buffer in memory) #### Response Example N/A ``` -------------------------------- ### ReadReplacingCurrentColor Source: https://context7.com/srwiley/oksvg/llms.txt Loads an SVG while replacing all instances of the CSS currentColor value with a specified color. ```APIDOC ## ReadReplacingCurrentColor ### Description Loads an SVG while replacing all instances of the CSS 'currentColor' value with a specified color, useful for dynamic theming. ### Parameters #### Parameters - **reader** (io.Reader) - Required - The input stream containing SVG data. - **color** (string) - Required - The replacement color (hex, rgb, or named color). - **mode** (ErrorMode) - Required - Controls how the parser handles unsupported SVG elements. ### Response - **icon** (*SvgIcon) - The parsed SVG icon structure with replaced colors. - **err** (error) - Error object if parsing fails. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.