将 BitmapImage 转换为 Bitmap,反之亦然
我有 C# 中的 BitmapImage。我需要对图像进行操作。例如灰度、在图像上添加文本等。
我在 stackoverflow 中找到了接受 Bitmap 并返回 Bitmap 的灰度函数。
所以我需要将BitmapImage转换为Bitmap,进行操作并转换回来。
我该怎么做?这是最好的方法吗?
I have BitmapImage in C#. I need to do operations on image. For example grayscaling, adding text on image, etc.
I have found function in stackoverflow for grayscaling which accepts Bitmap and returns Bitmap.
So I need to convert BitmapImage to Bitmap, do operation and convert back.
How can I do this? Is this best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
不需要使用国外的库。
将 BitmapImage 转换为 Bitmap:
将 Bitmap 转换回 BitmapImage:
There is no need to use foreign libraries.
Convert a BitmapImage to Bitmap:
To convert the Bitmap back to a BitmapImage:
这是将 Bitmap 转换为 BitmapImage 的扩展方法。
Here's an extension method for converting a Bitmap to BitmapImage.
如果您只需要从 BitmapImage 转到 Bitmap 这很容易,
If you just need to go from BitmapImage to Bitmap it's quite easy,
使用 System.Windows.Interop;
...
using System.Windows.Interop;
...
我刚刚尝试在我的代码中使用上述内容,并且我相信 Bitmap2BitmapImage 函数(也可能是另一个函数)存在问题。
上面的行是否会导致流被丢弃?这意味着返回的 BitmapImage 丢失了其内容。
由于我是 WPF 新手,我不确定这是正确的技术解释,但在我删除 using 指令之前,代码在我的应用程序中不起作用。
I've just been trying to use the above in my code and I believe that there is a problem with the Bitmap2BitmapImage function (and possibly the other one as well).
Does the above line result in the stream being disposed of? Which means that the returned BitmapImage loses its content.
As I'm a WPF newbie I'm not sure that this is the correct technical explanation, but the code didn't work in my application until I removed the using directive.
这里是异步版本。
Here the async version.
谢谢吉列尔莫·埃尔南德斯,我创建了一个可以工作的代码变体。我在这段代码中添加了命名空间以供参考。
Thanks Guillermo Hernandez, I created a variation of your code that works. I added the namespaces in this code for reference.
这将从 System.Drawing.Bitmap 转换为 BitmapImage:
This converts from System.Drawing.Bitmap to BitmapImage: