1 private void SetSource(System.Windows.Controls.Image image, string fileName) 2 { 3 System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(fileName); 4 int imageWidth = 0, imageHeight = 0; 5 InitializeImageSize(sourceImage, image, out imageWidth, out imageHeight); 6 7 Bitmap sourceBmp = new Bitmap(sourceImage, imageWidth, imageHeight); 8 IntPtr hBitmap = sourceBmp.GetHbitmap(); 9 BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty,10 BitmapSizeOptions.FromEmptyOptions());11 bitmapSource.Freeze();12 WriteableBitmap writeableBmp = new WriteableBitmap(bitmapSource);13 sourceImage.Dispose();14 sourceBmp.Dispose();15 image.Source = writeableBmp;16 }17 18 ///19 /// Initialize ImageSize.20 /// 21 /// 22 /// 23 /// 24 /// 25 private static void InitializeImageSize(System.Drawing.Image sourceImage, System.Windows.Controls.Image image,26 out int imageWidth, out int imageHeight)27 {28 int width = sourceImage.Width;29 int height = sourceImage.Height;30 float aspect = (float)width / (float)height;31 if (image.Height != double.NaN)32 {33 imageHeight = Convert.ToInt32(image.Height);34 imageWidth = Convert.ToInt32(aspect * imageHeight);35 }36 else if (image.Width != double.NaN)37 {38 imageWidth = Convert.ToInt32(image.Width);39 imageHeight = Convert.ToInt32(image.Width / aspect);40 }41 else42 {43 imageHeight = 100;44 imageWidth = Convert.ToInt32(aspect * imageHeight);45 }46 }
调用: SetSource(this.imageCur, “C:\1.png”);