WPF 完美截图 <二>

根据WPF 完美截图 <一>总结:

1.BitmapSource与BitmapImage及CorppedBitmap之间的转换

2.中心及边角的模板实现及其拖动

3.除了拖动矩形外区域要实现遮罩,遮罩的实现

今天实现第一个技术点,各类型间的转换,代码均为网上搜集。

BitmapSourceToBitmapImage转换:

     private BitmapImage BitmapSourceToBitmapImage(BitmapSource bitmapSource)
        {
            var encoder = new JpegBitmapEncoder();
            var memoryStream = new MemoryStream();
            var bImg = new BitmapImage();

            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(memoryStream);

            bImg.BeginInit();
            bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
            bImg.EndInit();

            memoryStream.Close();

            return bImg;
        }

ByteArrayToBitmapImage转换:

       private BitmapImage ByteArrayToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;

            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }

            return bmp;
        }

BitmapImageToByteArray转换:

      private byte[] BitmapImageToByteArray(BitmapImage bmp)
        {
            byte[] byteArray = null;
            try
            {
                Stream sMarket = bmp.StreamSource;
                if (sMarket != null && sMarket.Length > 0)
                {
                    sMarket.Position = 0;
                    using (BinaryReader br = new BinaryReader(sMarket))
                    {
                        byteArray = br.ReadBytes((int)sMarket.Length);
                    }
                }
            }
            catch
            {
                //other exception handling 
            }
            return byteArray;
        }
原文地址:https://www.cnblogs.com/avictor/p/3469118.html