c# svg转Bitmap Bitmap转ImageSource

需要安装nuget包【svg】

public class SVGHelper
    {
        /// <summary>
        /// 保持svg为图片
        /// </summary>
        /// <param name="path"></param>
        /// <param name="imgPath"></param>
        /// <returns></returns>
        public static void SaveSVGImg(string path,string imgPath)
        {
            var svgContent = File.ReadAllText(path);
            // 使用SvgDocument解析SVG内容
            SvgDocument svgDocument = SvgDocument.FromSvg<SvgDocument>(svgContent);

            // 将SvgDocument转换为Drawing对象
            System.Drawing.Bitmap bitmap = svgDocument.Draw();
            bitmap.Save(imgPath);
        }

        /// <summary>
        /// SVG转Bitmat然后再转为ImageSource
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ImageSource ConvertSvgToDrawingImage(string path)
        {
            var svgContent = File.ReadAllText(path);
            // 使用SvgDocument解析SVG内容
            SvgDocument svgDocument = SvgDocument.FromSvg<SvgDocument>(svgContent);

            // 将SvgDocument转换为Drawing对象
            System.Drawing.Bitmap bitmap = svgDocument.Draw();
            var imageSource = ToImageSource(bitmap);
            return imageSource;
        }

        /// <summary>
        /// Bitmap转ImageSource
        /// </summary>
        /// <param name="hObject"></param>
        /// <returns></returns>
        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
        public static ImageSource ToImageSource( Bitmap bitmap)
        {
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
            // 记得要进行内存释放。否则会有内存不足的报错。
            if (!DeleteObject(hBitmap))
            {
                throw new Win32Exception();
            }
            return wpfBitmap;
        }
    }
posted @ 2024-08-08 22:19  Hey,Coder!  阅读(227)  评论(0)    收藏  举报