c# svg轉Bitmap Bitmap轉ImageSource

Hey,Coder!發表於2024-08-08

需要安裝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;
        }
    }

相關文章