c# - 将 TransformedBitmap 对象保存到磁盘。

标签 c# wpf image bitmap save

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

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

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

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

最佳答案

您的所有编码器都使用 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 作为通用类型参数。

希望这有帮助。

关于c# - 将 TransformedBitmap 对象保存到磁盘。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3659046/

相关文章:

c# - 在 C# 中索引到任意级别的数组

c# - TabControl 未找到 TabControl 项的数据模板

wpf - 没有 BitmapEffects 的 OuterGlowBitmapEffect 替代方案

Java图像被剪切

c# - 如何快速将 byte[] 转换为字符串?

c# - 我应该如何使用 Entity Framework 实体分部类?

java - 如何将bmp图像转换成DICOM文件?

iphone - 如何在 UITableView 中用图像填充一行

c# - 使用 LINQ 通过单个查询获取外键表

wpf - 如何格式化标签以具有显示格式字符串?