從Resource、Content、stream、Bytes取得Image
最近在寫Silverlight,處裡一些與圖片有關的東西,會需要時常從Resource, Content等位置取得Image,然後填入Silverlight的Image物件,有時候則是透過WebClient取得stream,有時候則是取得一堆的bytes...總之呢,有各種不同的情境。
所幸整理了一下,
如果要從Content中取得Image,則可參考底下的這段程式碼:
其實概念上是一樣的,只是多了一段從Bytes轉ImageSource的部分,也剛好順便看一下從bytes抓取Image到BitmapImage的方法:
底下這段Code則是從特定url取得Image
這些都是從特定資料來源取得Image的方法,在WP7和Silverlight當中都挺好用...
BTW, 上面的程式碼我留了一些可簡化的空間,有興趣的朋友可以研究看看^^
分享
所幸整理了一下,
//從特定Path的Resource取得Image
public static System.Windows.Media.Imaging.BitmapImage GetImageFromResourcePath(string path)
{
return new System.Windows.Media.Imaging.BitmapImage(new Uri(path, UriKind.Relative));
}這邊要注意的是,UriKind務必是Relative,別設為Absolute。如果要從Content中取得Image,則可參考底下的這段程式碼:
/// 取得content類型的資源
public static System.Windows.Media.Imaging.BitmapImage GetImageFromContentPath(string path)
{
//直接抓檔案版本
Uri fileUri = new Uri(path, UriKind.Relative);
StreamResourceInfo streamResourceInfo = Application.GetResourceStream(fileUri);
using (BinaryReader br = new BinaryReader(streamResourceInfo.Stream))
{
byte[] content = br.ReadBytes((int)br.BaseStream.Length);
return aRock.Phone.Images.ByteToImageSource(content);
}
}其實概念上是一樣的,只是多了一段從Bytes轉ImageSource的部分,也剛好順便看一下從bytes抓取Image到BitmapImage的方法:
/// 取得byte型態的Image
public static BitmapImage ByteToImageSource(byte[] imageBytes)
{
BitmapImage im = new BitmapImage();
MemoryStream ms = new MemoryStream(imageBytes);
im.SetSource(ms);
return im;
}底下這段Code則是從特定url取得Image
WebClient wc = new WebClient();
Uri url = new Uri("filename", UriKind.Absolute);
//取得資料後
wc.OpenReadCompleted += (ss,arg) => {
//把resource填入BitmapImage
BitmapImage bi = new BitmapImage();
bi.SetSource(arg.Result);
//把BitmapImage填入Image
img.Source = bi;
};
//非同步讀取遠端資料(ImagesBytes)
wc.OpenReadAsync(url);
這些都是從特定資料來源取得Image的方法,在WP7和Silverlight當中都挺好用...
BTW, 上面的程式碼我留了一些可簡化的空間,有興趣的朋友可以研究看看^^
分享
留言
請問該怎麼做呢?是要將QRcode圖片顯示於image是嗎??