(转)Silverlight显示本地图片、Stream转Byte数组

转载自:http://www.cnblogs.com/forgetu/archive/2010/08/07/silverlight-load-local-image-stream-to-byte-array.html#commentform

通过 OpenFileDialog 浏览本地图片,然后将图片读取到文件流中,再将文件流转成 BitmapImage 就可以显示本地图片了。代码中ImageFromStream是一个Image控件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Image files|*.jpg|All files|*.*";
dlg.FilterIndex = 1;
dlg.Multiselect = false;
bool? result = dlg.ShowDialog().Value;
 
if (result == true)
{
    FileStream fileStream = dlg.File.OpenRead();
                 
    BitmapImage image = new BitmapImage();
    image.SetSource(fileStream);
 
    ImageFromStream.Source = image;
 
    fileStream.Close();

 

将Stream转成Byte数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private byte[] StreamToBytes(Stream stream)
{
    using (MemoryStream ms = new MemoryStream())
    {
        byte[] buffer = new byte[8 * 1024];
        int read = 0;
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
 
        return ms.ToArray();
    }
}
posted @ 2012-05-14 22:02  槑槑  阅读(462)  评论(0编辑  收藏  举报