C# WPF Image控件下对于Base64的转化显示

原文: C# WPF Image控件下对于Base64的转化显示

算作前言

本文对图片如何转化成base64不做描述,我们可以从很多途径了解到转化办法。却很少有博客提到怎么在WPF的Image控件中显示图片。

对于base64的合法性

随便拿一张图片转一下试一试:

额。好长....取前面一部分吧

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC4AAAA9CAMAAADlJaswAAAAe1BMVE.....

C#对于这段数据,通常的做法是:

try
{
    byte[] streamBase = Convert.FromBase64String(base64);
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

抛出了异常:

输入的不是有效的 Base-64 字符串,因为它包含非 Base-64 字符、两个以上的填充字符,或者填充字符间包含非法字符。

明明是正常转化得来的,为什么却是不合法的字符串?其实这里还需要一点处理,就算把头部信息去掉!

//base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
string imagebase64 = base64.Substring(base64.IndexOf(",") + 1);

这样就可以成功转化了。现在来看怎么显示在Image里面。

WPF中Image显示

 答案:https://stackoverflow.com/questions/593388/how-do-i-read-a-base64-image-in-wpf

string imagebase64 = base64.Substring(base64.IndexOf(",") + 1);
byte[] streamBase = Convert.FromBase64String(imagebase64);
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = new MemoryStream(streamBase);
bi.EndInit();
Image.Source = bi;

没啥太花里胡哨的东西。

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/10703861.html