我有一个 WPF 控件,其中包含带图像的面板。我正在尝试对其进行序列化,以便它可以独立加载,而不必在本地文件夹中包含图像。
我知道我可以将图像存储为 Base64 字符串,然后可能将其加载备份,但我想做的是包装 ImageSource 类以接受 Base64 字符串作为源。
我仔细研究了 ImageSource 类,但我相信我对它的工作原理还不够了解。当我在我的自定义包装器类中实现 ImageSource 时,我得到了 2 个我不清楚的方法:
元数据
创建实例核心
我想知道是否有人可以阐明这些方法,或者指出一个不会让我回到 MSDN 文档的方向。
最佳答案
此类包装了一个从 base64 字符串属性初始化的 BitmapImage:
public class Base64BitmapImage : BitmapSource
{
private BitmapImage bitmap;
private string base64Source;
public string Base64Source
{
get { return base64Source; }
set
{
base64Source = value;
bitmap = new BitmapImage();
if (DecodeFailed != null)
{
bitmap.DecodeFailed += DecodeFailed;
}
using (var stream = new MemoryStream(Convert.FromBase64String(base64Source)))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
if (DecodeFailed != null)
{
bitmap.DecodeFailed -= DecodeFailed;
}
bitmap.Freeze();
}
}
public override event EventHandler<ExceptionEventArgs> DecodeFailed;
public override bool IsDownloading
{
get { return false; }
}
public override PixelFormat Format
{
get { return bitmap != null ? bitmap.Format : base.Format; }
}
public override double DpiX
{
get { return bitmap != null ? bitmap.DpiX : base.DpiX; }
}
public override double DpiY
{
get { return bitmap != null ? bitmap.DpiY : base.DpiY; }
}
public override double Width
{
get { return bitmap != null ? bitmap.Width : base.Width; }
}
public override double Height
{
get { return bitmap != null ? bitmap.Height : base.Height; }
}
public override int PixelWidth
{
get { return bitmap != null ? bitmap.PixelWidth : base.PixelWidth; }
}
public override int PixelHeight
{
get { return bitmap != null ? bitmap.PixelHeight : base.PixelHeight; }
}
public override ImageMetadata Metadata
{
get { return bitmap != null ? bitmap.Metadata : base.Metadata; }
}
public override void CopyPixels(Array pixels, int stride, int offset)
{
if (bitmap != null)
{
bitmap.CopyPixels(pixels, stride, offset);
}
}
public override void CopyPixels(Int32Rect sourceRect, Array pixels, int stride, int offset)
{
if (bitmap != null)
{
bitmap.CopyPixels(sourceRect, pixels, stride, offset);
}
}
public override void CopyPixels(Int32Rect sourceRect, IntPtr buffer, int bufferSize, int stride)
{
if (bitmap != null)
{
bitmap.CopyPixels(sourceRect, buffer, bufferSize, stride);
}
}
protected override Freezable CreateInstanceCore()
{
var instance = new Base64BitmapImage();
instance.bitmap = bitmap;
instance.base64Source = base64Source;
return instance;
}
}
可以这样使用:
<Image>
<Image.Source>
<local:Base64BitmapImage Base64Source="..."/>
</Image.Source>
</Image>
关于c# - 包装 ImageSource 用于 Base64 图片序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16086697/