由于一些数据存储限制(noSQL),我需要将图像存储为字符串。 如何将图像位图序列化为字符串并返回。 这是我的做法:
Uri testImageUri = new Uri("/DictionaryBasedVM;component/test.jpg", UriKind.Relative);
StreamResourceInfo sri = Application.GetResourceStream(testImageUri);
var stringData = GetString(sri.Stream);
ImageSource = stringData;
哪里
ImageControl只是 xaml 中定义的 silverlight 图像控件。
我正在使用以下实用函数:
//For testing
public static string GetString(Stream stream)
{
byte[] byteArray = ReadFully(stream);
return Encoding.Unicode.GetString(byteArray,0,byteArray.Length);
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
以及以下属性:
private string _ImageSource = "";
public string ImageSource
{
set
{
_ImageSource = value;
byte[] byteArray = Encoding.Unicode.GetBytes(value);
MemoryStream imageStream = new MemoryStream(byteArray);
BitmapImage imageSource = new BitmapImage();
imageSource.SetSource(imageStream);
ImageControl.Source = imageSource;
}
get
{
return _ImageSource;
}
}
我收到错误:“灾难性故障(HRESULT 异常:0x8000FFFF (E_UNEXPECTED))”,如下所示:
即使我不将其存储为字符串,我仍然很好奇为什么我不能这样做。
最佳答案
Unicode 可能不是用于此目的的最佳编码。您最好对 byte[]
进行 Base64 编码并存储它。
关于c# - 从字符串加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6040710/