将 BitmapImage 转换为 Bitmap,反之亦然 [英] Converting BitmapImage to Bitmap and vice versa

查看:39
本文介绍了将 BitmapImage 转换为 Bitmap,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中有 BitmapImage.我需要对图像进行操作.例如灰度,在图像上添加文本等.

I have BitmapImage in C#. I need to do operations on image. For example grayscaling, adding text on image, etc.

我在 stackoverflow 中找到了用于灰度缩放的函数,它接受 Bitmap 并返回 Bitmap.

I have found function in stackoverflow for grayscaling which accepts Bitmap and returns Bitmap.

所以我需要把BitmapImage转换成Bitmap,做操作再转换回来.

So I need to convert BitmapImage to Bitmap, do operation and convert back.

我该怎么做?这是最好的方法吗?

How can I do this? Is this best way?

推荐答案

无需使用国外库.

将位图图像转换为位图:

Convert a BitmapImage to Bitmap:

private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

    using(MemoryStream outStream = new MemoryStream())
    {
        BitmapEncoder enc = new BmpBitmapEncoder();
        enc.Frames.Add(BitmapFrame.Create(bitmapImage));
        enc.Save(outStream);
        System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

        return new Bitmap(bitmap);
    }
}

要将位图转换回位图图像:

To convert the Bitmap back to a 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;
}

这篇关于将 BitmapImage 转换为 Bitmap,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆