剛接觸WPF,很多地方都不懂,就把自己遇到的一些問題記錄下來,以便日後回過頭來看看。
開始使用Image控件,不知道怎麼去顯示圖檔,在同僚指導下知道了BitmapImage 類,用來顯示在Image中顯示圖檔,按F1進入幫助文檔,找到相關的定義:
// Create the image element.
Image simpleImage = new Image();
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);
// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/sampleImages/cherries_larger.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;
建立一個WPF項目,在工具箱中拖出一個Imag
e控件
選擇一個合适的圖檔,按照主視窗Load事件中寫自己的代碼
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"F:\1.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
image1.Source = bi;
}
圖檔如下:
看到圖檔整個人都不好了。
後面看到了一篇文章,覺得說的挺好的。http://www.cnblogs.com/zydf/p/3141735.html
的确處理單張圖檔挺好用的,擔當處理多張的時候,就要考慮記憶體的問題了。先把圖檔緩存成二進制,這樣可以釋放對圖檔檔案資源的占用,後面代碼執行效率高;
就自己做出了下面的修改:
private string path = @"F:\1.jpg";
private void Window_Loaded(object sender, RoutedEventArgs e)
{
using (BinaryReader loader = new BinaryReader(File.Open(path, FileMode.Open)))
{
FileInfo fd = new FileInfo(path);
int Length = (int)fd.Length;
byte[] buf = new byte[Length];
buf = loader.ReadBytes((int)fd.Length);
loader.Dispose();
loader.Close();
//開始加載圖像
BitmapImage bim = new BitmapImage();
bim.BeginInit();
bim.StreamSource = new MemoryStream(buf);
bim.EndInit();
image1.Source = bim;
GC.Collect(); //強制回收資源
}
//BitmapImage bi = new BitmapImage();
BitmapImage.UriSource must be in a BeginInit/EndInit block.
//bi.BeginInit();
//bi.UriSource = new Uri(@"F:\1.jpg",UriKind.RelativeOrAbsolute);
//bi.EndInit();
//image1.Source = bi;
}
圖檔效果:
它又出來了!
當然,後面就可以做更多的事情啦。