private void SetSource(System.Windows.Controls.Image image, string fileName) { System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(fileName); int imageWidth = 0, imageHeight = 0; InitializeImageSize(sourceImage, image, out imageWidth, out imageHeight); Bitmap sourceBmp = new Bitmap(sourceImage, imageWidth, imageHeight); IntPtr hBitmap = sourceBmp.GetHbitmap(); BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bitmapSource.Freeze(); WriteableBitmap writeableBmp = new WriteableBitmap(bitmapSource); sourceImage.Dispose(); sourceBmp.Dispose(); image.Source = writeableBmp; } /// <summary> /// Initialize ImageSize. /// </summary> /// <param name="sourceImage"></param> /// <param name="image"></param> /// <param name="imageWidth"></param> /// <param name="imageHeight"></param> private static void InitializeImageSize(System.Drawing.Image sourceImage, System.Windows.Controls.Image image, out int imageWidth, out int imageHeight) { int width = sourceImage.Width; int height = sourceImage.Height; float aspect = (float)width / (float)height; if (image.Height != double.NaN) { imageHeight = Convert.ToInt32(image.Height); imageWidth = Convert.ToInt32(aspect * imageHeight); } else if (image.Width != double.NaN) { imageWidth = Convert.ToInt32(image.Width); imageHeight = Convert.ToInt32(image.Width / aspect); } else { imageHeight = 100; imageWidth = Convert.ToInt32(aspect * imageHeight); } }
|
|