答案:在C#中将Base64字符串转换为图片需先去除data:image/{类型};base64,前缀,再用Convert.FromBase64String解码为字节数组,接着通过MemoryStream创建Image对象并保存。1. 检查并截取逗号后有效Base64内容;2. 解码为byte[];3. 使用using(MemoryStream)和Image.FromStream加载图像;4. 调用Save输出文件。需捕获FormatException等异常确保健壮性,完整流程包含前缀处理、解码、流操作与资源释放。

在 C# 中将 Base64 字符串转换为图片是一个常见的需求,比如处理前端传来的图像数据、保存用户上传的头像等。实现过程并不复杂,核心是将 Base64 字符串解码为字节数组,再通过内存流创建图像对象。
Base64 编码的图片通常以 data:image/{类型};base64, 开头,例如:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...在转换前需要先移除前面的 MIME 类型声明部分,只保留真正的 Base64 内容。
使用 Substring 或 IndexOf 判断是否存在前缀,并提取有效 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);将字节数组写入内存流,然后用 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 确保资源释放。
以下是一个完整的控制台示例:
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 字符串完整、无多余字符,并正确处理前缀和异常,就能稳定实现转换。
以上就是C# 如何将 Base64 字符串转换为图片_C# Base64 转图片实现指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号