首页 >后端开发 >C++ >如何将图像转换为字节数组并返回C#?

如何将图像转换为字节数组并返回C#?

Linda Hamilton
Linda Hamilton原创
2025-01-26 03:26:09401浏览

How to Convert an Image to a Byte Array and Back in C#?

在 C# 中将图像转换为字节数组并返回

本文演示了如何在 C# 环境中高效地将图像转换为字节数组,反之亦然,重点介绍适合 WPF 应用程序的方法。

方法一:使用MemoryStream

ImageToByteArray 方法利用 MemoryStream 来捕获图像数据。图像使用其原始格式保存到流中,并返回结果字节数组。

<code class="language-csharp">public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using (var ms = new MemoryStream())
    {
        imageIn.Save(ms, imageIn.RawFormat);
        return ms.ToArray();
    }
}</code>

方法二:使用Image类直接转换

C# 提供了用于简化图像到字节数组转换的内置功能:

<code class="language-csharp">
// Convert image to byte array
byte[] imageArray = Image.FromFile("image.jpg").ToByteArray();

// Convert byte array to image
Image convertedImage = Image.FromByteArray(imageArray);
```  This approach simplifies the process, eliminating the need for manual stream handling.  Remember to handle potential exceptions (e.g., `FileNotFoundException`).</code>

以上是如何将图像转换为字节数组并返回C#?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn