C# 如何将 Base64 字符串转换为图片_C# Base64 转图片实现指南

来源:这里教程网 时间:2026-02-21 17:29:44 作者:

在 C# 中将 Base64 字符串转换为图片是一个常见的需求,比如处理前端传来的图像数据、保存用户上传的头像等。实现过程并不复杂,核心是将 Base64 字符串解码为字节数组,再通过内存流创建图像对象。

1. 理解 Base64 图片字符串格式

Base64 编码的图片通常以 data:image/{类型};base64, 开头,例如:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...

在转换前需要先移除前面的 MIME 类型声明部分,只保留真正的 Base64 内容。

2. 去除 Data URI 前缀并解码

使用 SubstringIndexOf 判断是否存在前缀,并提取有效 Base64 数据:

string base64String = originalString; int indexOfComma = originalString.IndexOf(","); if (indexOfComma > 0 && originalString.StartsWith("data:image")) { base64String = originalString.Substring(indexOfComma + 1); } byte[] imageBytes = Convert.FromBase64String(base64String);

3. 使用 MemoryStream 创建 Image 对象

将字节数组写入内存流,然后用 Image.FromStream 加载图片:

using (MemoryStream ms = new MemoryStream(imageBytes)) { Image image = Image.FromStream(ms); // 可保存到文件或赋值给 PictureBox image.Save("output.png", System.Drawing.Imaging.ImageFormat.Png); }

注意:MemoryStream 和 Image 都实现了 IDisposable,建议用 using 确保资源释放。

4. 完整示例代码

以下是一个完整的控制台示例:

string base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAE..."; try { int idx = base64.IndexOf("base64,"); if (idx != -1) base64 = base64.Substring(idx + 7);
byte[] bytes = Convert.FromBase64String(base64);
using (MemoryStream ms = new MemoryStream(bytes))
{
    using (Image img = Image.FromStream(ms))
    {
        img.Save("decoded_image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
        Console.WriteLine("图片已保存!");
    }
}

} catch (FormatException) { Console.WriteLine("Base64 格式错误"); } catch (Exception ex) { Console.WriteLine("转换失败: " + ex.Message); }

基本上就这些。只要确保 Base64 字符串完整、无多余字符,并正确处理前缀和异常,就能稳定实现转换。

相关推荐