将BitmapImage转换为Bitmap,反之亦然

将BitmapImage转换为Bitmap,反之亦然,第1张

将BitmapImage转换为Bitmap,反之亦然

无需使用外部库。

将BitmapImage转换为Bitmap:

private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage){    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));    using(MemoryStream outStream = new MemoryStream())    {        BitmapEnprer enc = new BmpBitmapEnprer();        enc.frames.Add(Bitmapframe.Create(bitmapImage));        enc.Save(outStream);        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);        return new Bitmap(bitmap);    }}

要将位图转换回BitmapImage:

[System.Runtime.InteropServices.Dllimport("gdi32.dll")]public static extern bool DeleteObject(IntPtr hObject);private BitmapImage Bitmap2BitmapImage(Bitmap bitmap){    IntPtr hBitmap = bitmap.GetHbitmap();    BitmapImage retval;    try    {        retval = (BitmapImage)Imaging.CreateBitmapSourceFromHBitmap(          hBitmap,          IntPtr.Zero,          Int32Rect.Empty,          BitmapSizeOptions.FromEmptyOptions());    }    finally    {        DeleteObject(hBitmap);    }    return retval;}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5150827.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存