Silverlight BitmapImage的SetSource(Stream streamSource)致命性错误的解决办法

 

这段时间做了些silverlight方面的项目,遇到了一些问题,但是磕磕绊绊的还是都解决了。今天先贴一个出来。

 

当我们用WebClient 从网络上获取图片流然后用BitmapImage绑定到前端的的Image的时候也许会遇到些意想不到的问题。

 

先给出些示例代码:

 

 1 public MainPage()
 2 
        {
 3 
            InitializeComponent();
 4 
           
 5 

 6             Uri uri = new Uri("http://localhost:2587/FileHandle/DisplayImage/569p.jpg");
 7             WebClient cilent = new
 WebClient();
 8             cilent.OpenReadCompleted += new
 OpenReadCompletedEventHandler(cilent_OpenReadCompleted);
 9 
            cilent.OpenReadAsync(uri);
10 
            
11 
        }
12 

13 void cilent_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
14 
        {
15             if (e.Error == null && e.Result != null
)
16 
            {
17                 Stream stream =
 e.Result;
18                 BitmapImage bitmap = new
 BitmapImage();
19 

20 
21                 try
22                 {
23 
                    bitmap.SetSource(stream);
24 
                }
25                 catch
 (Exception ex)
26 
                {
27 
                }
28                 this.img.Source =
 bitmap;
29 
            }
30         } 

这个

http://localhost:2587/FileHandle/DisplayImage/569p.jpg URL其实是mvc端,FileHandle是controller,DisplayImage是Action,569p.jpg是参数。图片是用mvc 生成的图片流,

 

public ActionResult DisplayImage(string fileName)
        {
            
if
 (String.IsNullOrEmpty(fileName))
            {
                
return new
 EmptyResult();
            }
            
string extName =
 Path.GetExtension(fileName);

            
string contentType =
 GetContentType(extName);
            
if
 (String.IsNullOrEmpty(contentType))
            {
                
return new
 EmptyResult();
            }

            StringBuilder sbFileFullPath 
= new
 StringBuilder();
            sbFileFullPath.Append(mConfiguration.FileSharePath);
            sbFileFullPath.Append(
@"\"
);
            sbFileFullPath.Append(fileName);
            
if (!
System.IO.File.Exists(sbFileFullPath.ToString()))
            {
                
return new
 EmptyResult();
            }
            Bitmap bitMap 
= new
 Bitmap(sbFileFullPath.ToString());

            
            
            
byte[] fileBytes = null
;
            
using (MemoryStream ms = new
 MemoryStream())
            {
                bitMap.Save(ms, GetImageFormat(extName));
                fileBytes 
=
 ms.ToArray();
            }

            
return
 File(fileBytes, contentType);
        }

 

服务器端的Bitmap对象的Save(Stream stream, ImageFormat format);一定要注意第二个参数ImageFormat format,如果这个格式设置出错的话,就算你把服务器端的这个Action的url放到浏览器里图片正常显示,但是在silverlight也不会正 常的。当silverlight执行到bitmap.SetSource(stream);就会报致命错误了。所以格式一定要匹配对。这个也许是silverlight的bug,无非是图片的格式不匹配,无法转换,最起码也不应该出致命性错误啊。

 

 

 

 

还有的如果在服务端把一个其他格式的图片文件后缀改成jpg格式的,也会出这样问题的。

原文地址:https://www.cnblogs.com/songtzu/p/2439952.html