图片资源相互转换

49 篇文章 13 订阅

1、System.Drawing.Bitmap 转换 System.Windows.Media.ImageSource (Bitmap => ImageSource)

#region Change Bitmap To ImageSource
    [System.Runtime.InteropServices.DllImport("gdi32.dll", SetLastError = true)]

    private static extern bool DeleteObject(IntPtr hObject);

    public static System.Windows.Media.ImageSource ChangeBitmapToImageSource(System.Drawing.Bitmap bitmap)
    {
        IntPtr hBitmap = bitmap.GetHbitmap();
        System.Windows.Media.ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
            hBitmap,
            IntPtr.Zero,
            System.Windows.Int32Rect.Empty,
            System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());

        if (!DeleteObject(hBitmap))//注意内存的释放,否则内容持续增大,导致内存不足
        {
            throw new System.ComponentModel.Win32Exception();
        }
        return wpfBitmap;

    }
    #endregion

2、String path => ImageSource

private static object lockObj = new object();
public static ImageSource BitmapFromFileWithCache(String source)
{
	var bitmap = new BitmapImage();
	try
	{
		if (System.IO.File.Exists(source))
		{
			using (Stream stream = System.IO.File.OpenRead(source))
			{
				if (stream != null)
				{
					lock (lockObj)
					{
						bitmap.BeginInit();
						bitmap.StreamSource = stream;
						bitmap.CacheOption = BitmapCacheOption.OnLoad;
						bitmap.EndInit();
						stream.Dispose();//释放占用的资源
					}
				}
			}
		}
	}
	catch (Exception ex)
	{

	}
	return bitmap;
}

3、Uri => ImageSource

private static object lockObj = new object();
public static ImageSource BitmapFromUri(Uri source)
{
	var bitmap = new BitmapImage();
	try
	{
		var temp = new BitmapImage(source);
		temp = null;
		lock (lockObj)
		{
			bitmap.BeginInit();
			bitmap.UriSource = source;
			bitmap.CacheOption = BitmapCacheOption.OnLoad;
			bitmap.EndInit();
		}
	}
	catch { }
	return bitmap;
}

4、Stream => ImageSource

private static object lockObj = new object();
public static ImageSource BitmapFromFileWithCache(Stream stream)
{
    var bitmap = new BitmapImage();
    try
    {
        if (stream != null)
        {
            lock (lockObj)
            {
                bitmap.BeginInit();
                bitmap.StreamSource = stream;
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.EndInit();
                stream.Dispose();//释放占用的资源
            }
        }
    }
    catch (Exception ex)
    {

    }
    return bitmap;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值