gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:19:38 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com