1. 程式人生 > >Wpf Bitmap(Image)Base64,Url,檔案Path,Stream轉BitmapSource(ImageSource),無需外部dll

Wpf Bitmap(Image)Base64,Url,檔案Path,Stream轉BitmapSource(ImageSource),無需外部dll

using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;

namespace CommonUtils
{
    /// <summary>
    /// Windows圖片處理
    /// </summary>
    public static class WindowsImage
    {
        #region BitmapSource
        /// <summary>
        /// 獲取圖片源
        /// </summary>
        public static BitmapSource GetSource(Stream stream)
        {
            //已驗證stream不可關閉
            return BitmapFrame.Create(stream);
        }

        /// <summary>
        /// 獲取圖片源
        /// </summary>
        public static BitmapSource GetSource(Image image)
        {
            return GetSource(image.Stream());
        }

        /// <summary>
        /// 獲取圖片源
        /// </summary>
        public static BitmapSource GetSource(byte[] bytes)
        {
            return GetSource(bytes.ToStream());
        }

        /// <summary>
        /// 獲取圖片源
        /// </summary>
        public static BitmapSource GetSourceFromBase64(string base64)
        {
            return GetSource(base64.Base64Decode());
        }

        /// <summary>
        /// 獲取圖片源
        /// </summary>
        public static BitmapSource GetSourceFromUrlOrPath(string urlOrPath)
        {
            return new BitmapImage(new Uri(urlOrPath));
        }
        #endregion

        /// <summary>
        /// 獲取截圖
        /// </summary>
        public static Bitmap GetScreenShoot()
        {
            Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.CopyFromScreen(new Point(0, 0), new Point(0, 0), bitmap.Size);
            graphics.Dispose();
            return bitmap;
        }
    }
}