c# - 从字符串加载图像

标签 c# .net silverlight silverlight-4.0

由于一些数据存储限制(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))”,如下所示: enter image description here

即使我不将其存储为字符串,我仍然很好奇为什么我不能这样做。

最佳答案

Unicode 可能不是用于此目的的最佳编码。您最好对 byte[] 进行 Base64 编码并存储它。

关于c# - 从字符串加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6040710/

相关文章:

c# - streamreader 的基本流位置使用单声道

c# - 在 MVVM WPF 中打开新窗口

sql-server - CRM 2011 Silverlight 存储过程

Silverlight:使列表框背景透明?

c# - 在 C# 中使用 Process 执行 dotnet 命令

c# - 使用相同的 HttpWebRequest obj 请求第二个 url

c# - 通过 TCP 套接字发送命令的最佳方式是什么?

c# - 通过 POST httprequest 传输文件到 hololens(错误 429)

c# - 是否应该重构此 C# 代码以改用 Lazy<T> 类?

silverlight - 单元测试 silverlight 这住在哪里?