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

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

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数组

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 @ 2010-08-07 14:02  forgetu  阅读(1674)  评论(1编辑  收藏  举报