将 TransformedBitmap 对象保存到磁盘。

JTo*_*and 2 c# wpf image bitmap save

在 WPF 和 C# 中工作,我有一个 TransformedBitmap 对象,我可以:

  1. 需要作为位图类型的文件保存到磁盘(理想情况下,我将允许用户选择是否将其保存为 BMP、JPG、TIF 等,不过,我还没有到那个阶段......)
  2. 需要转换为 BitmapImage 对象,因为我知道如何从 BitmapImage 对象获取 byte[]。

不幸的是,在这一点上,我真的很难完成这两件事中的任何一件。

任何人都可以提供任何帮助或指出我可能缺少的任何方法吗?

Eug*_*rda 5

您的所有编码器都使用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;
        }
Run Code Online (Sandbox Code Playgroud)

它们接受任何 BitmapSource 作为第一个参数,接受任何 BitmapEncoder 作为泛型类型参数。

希望这可以帮助。