这段时间做了些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.openReadCoR_747_11845@pleted += new
OpenReadCoR_747_11845@pletedEventHandler(cilent_OpenReadCoR_747_11845@pleted);
9
cilent.openReadAsync(uri);
10
11
}
12
13 void cilent_OpenReadCoR_747_11845@pleted(object
sender, OpenReadCoR_747_11845@pletedEventArgs 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格式的,也会出这样问题的。
4YEAR MVC SILVERLIGHT