您的所有编码器都使用BitmapFrame类来创建将添加到Frames编码器集合属性的帧。BitmapFrame.Create方法有多种重载,其中之一接受BitmapSource类型参数。所以我们知道TransformedBitmap继承自BitmapSource我们可以将它作为参数传递给BitmapFrame.Create方法。以下是按照您描述的方式工作的方法:
public bool WriteTransformedBitmapToFile<T>(BitmapSource bitmapSource, string fileName) where T : BitmapEncoder, new()
        {
            if (string.IsNullOrEmpty(fileName) || bitmapSource == null)
                return false;
            //creating frame and putting it to Frames collection of selected encoder
            var frame = BitmapFrame.Create(bitmapSource);
            var encoder = new T();
            encoder.Frames.Add(frame);
            try
            {
                using (var fs = new FileStream(fileName, FileMode.Create))
                {
                    encoder.Save(fs);
                }
            }
            catch (Exception e)
            {
                return false;
            }
            return true;
        }
        private BitmapImage GetBitmapImage<T>(BitmapSource bitmapSource) where T : BitmapEncoder, new()
        {
            var frame = BitmapFrame.Create(bitmapSource);
            var encoder = new T();
            encoder.Frames.Add(frame);
            var bitmapImage = new BitmapImage();
            bool isCreated;
            try
            {
                using (var ms = new MemoryStream())
                {
                    encoder.Save(ms);
                    ms.Position = 0;
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = ms;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                    isCreated = true;
                }
            }
            catch
            {
                isCreated = false;
            }
            return isCreated ? bitmapImage : null;
        }
它们接受任何 BitmapSource 作为第一个参数,接受任何 BitmapEncoder 作为泛型类型参数。
希望这可以帮助。
| 归档时间: | 
 | 
| 查看次数: | 3523 次 | 
| 最近记录: |