c#将图片转为数据流
时间: 2025-02-22 21:57:56 浏览: 40
### 将图像转换为数据流
在C#中,可以利用`System.Drawing.Bitmap`类来加载图像,并通过`MemoryStream`将其转换成字节流。以下是具体实现方法:
```csharp
using System;
using System.Drawing;
using System.IO;
namespace ImageToStreamExample {
class Program {
static void Main(string[] args) {
string imagePath = "path_to_your_image_file"; // 图像路径
using (Bitmap bitmap = new Bitmap(imagePath)) {
using (MemoryStream ms = new MemoryStream()) {
// 将图像保存到内存流中
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
Console.WriteLine($"Image converted to stream with length: {imageBytes.Length} bytes");
}
}
Console.ReadKey();
}
}
}
```
此代码片段展示了如何读取指定路径下的图像文件并创建位图对象[^1]。接着使用`MemoryStream`作为中介存储媒介,最终得到表示该图像的字节数组。
阅读全文
相关推荐


















