You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

新手求助:如何用SkiaSharp按坐标裁剪SVG并转换为PNG?

SVG裁剪为指定矩形并转PNG的SkiaSharp实现问题

我有一张较大的SVG图片,需要通过坐标将其裁剪为矩形并转换为PNG格式。我是C#绘图领域的新手,对Surface、Canvas等概念并不熟悉。

已完成的步骤

我已成功使用SkiaSharp.Extended.Svg加载SVG:

var svg = new SkiaSharp.Extended.Svg.SKSvg();
svg.Load(tmpPath);

存在的疑问

我找到了一段保存PNG的代码,但无法理解其逻辑:

var imageInfo = new SKImageInfo(100, 100);
using (var surface = SKSurface.Create(imageInfo))
using (var canvas = surface.Canvas)
{
    // calculate the scaling need to fit to screen
    var scaleX = 100 / svg.Picture.CullRect.Width;
    var scaleY = 100 / svg.Picture.CullRect.Height;
    var matrix = SKMatrix.CreateScale((float)scaleX, (float)scaleY);

    // draw the svg
    canvas.Clear(SKColors.Transparent);
    canvas.DrawPicture(svg.Picture, ref matrix);
    canvas.Flush();

    using (var data = surface.Snapshot())
    using (var pngImage = data.Encode(SKEncodedImageFormat.Png, 100))
    {
        tmpPath = Path.ChangeExtension(tmpPath, "PNG");
        using var imageStream = new FileStream(tmpPath, FileMode.Create);
        pngImage.SaveTo(imageStream);
    }
}

尝试实现后遇到的问题

我自行编写了裁剪转换代码,但生成的PNG是透明空图:

private string ConvertSVGToPNGRectangleWithSkiaSharpExtended(string path, double left, double top, double right, double bottom)
{
    var svg = new SkiaSharp.Extended.Svg.SKSvg();
    var picture = svg.Load(path);

    // Get the initial map size
    var source = new SKRect(picture.CullRect.Left, picture.CullRect.Top, picture.CullRect.Width, picture.CullRect.Height);

    // Cropping Rect
    var cropRect = new SKRect((int)left, (int)top, (int)right, (int)bottom);

    var croppedBitmap = new SKBitmap((int)cropRect.Width, (int)cropRect.Height);

    using var canvas = new SKCanvas(croppedBitmap);
    canvas.Clear(SKColors.Transparent);
    canvas.DrawBitmap(croppedBitmap, source, cropRect);

    var data = croppedBitmap.Encode(SKEncodedImageFormat.Png, 100);

    path = Path.ChangeExtension(path, "PNG");
    using var imageStream = new FileStream(path, FileMode.Create);
    data.SaveTo(imageStream);

    return path;
}

恳请指点解决方向。

内容的提问来源于stack exchange,提问作者anon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 19:27:16