c# - 将 BitmapImage 转换为位图,反之亦然

标签 c# .net bitmap

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

我在 stackoverflow 中找到了接受位图并返回位图的灰度函数。

所以我需要将BitmapImage转换成Bitmap,进行运算再转换回来。

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

最佳答案

无需使用国外库

将 BitmapImage 转换为位图:

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

将位图转换回位图图像:

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

关于c# - 将 BitmapImage 转换为位图,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6484357/

相关文章:

C# 定点转浮点

c# - 让 .Net 应用程序在崩溃时关闭

c# - 文件未正确读取 Visual Studio 中 ASPX 文件的输入

asp.net - 当 api 在另一个站点下创建为 Web 应用程序时,路由失败

c# - 接口(interface)属性的内部修饰符

c# - 如何在字典的第一个索引中插入元素?

c# - 如何在 C# 中制作 Observable Hashset?

android - 透明位图为黑色

android - 文件的图像 URI

android - 如何将存储在数据库中的图像作为字符串显示为真实图像?