C# 图片转base64字符串
时间: 2024-07-01 14:01:01 浏览: 18
在C#中,将图片转换为Base64字符串通常用于Web应用程序中,尤其是在发送图像作为HTTP响应内容或者存储到数据库时,因为Base64编码可以将二进制数据转换成文本格式。以下是一个简单的步骤来实现这个功能:
```csharp
using System;
using System.Drawing;
using System.IO;
using System.Text;
public string ImageToBase64(string imagePath)
{
byte[] imageBytes = null;
try
{
// 读取图片文件
using (Image img = Image.FromFile(imagePath))
{
// 创建MemoryStream
using (MemoryStream ms = new MemoryStream())
{
// 将图片保存到MemoryStream中
img.Save(ms, img.RawFormat);
// 获取Base64字符串
imageBytes = ms.ToArray();
}
}
}
catch (Exception ex)
{
// 处理异常
Console.WriteLine($"Error: {ex.Message}");
return null;
}
// 返回Base64字符串
return Convert.ToBase64String(imageBytes, Base64FormattingOptions.InsertLineBreaks); // 添加换行符以便于阅读
}
```
相关推荐
![exe](https://img-home.csdnimg.cn/images/20210720083343.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)