WPF中Image显示本地图片(转)

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);
}
}

 

调用:  SetSource(this.imageCur, “C:\1.png”);

 

http://www.cnblogs.com/yunyou/archive/2013/01/25/2876054.html

posted on 2014-05-27 16:45  ExplorerMan  阅读(1549)  评论(0编辑  收藏  举报

导航