You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6控制台程序如何将Base64字符串转为图片并保存到文件系统?

在.NET 6控制台应用中将Base64字符串转换为图片文件保存

你不需要依赖Image.Save()方法——直接将Base64字符串解码为字节数组后写入文件即可,这是更高效且跨平台的方案,同时避开了.NET 6中System.Drawing.Common的平台限制问题。

实现步骤:

  • 移除Base64字符串可能带有的前缀(如data:image/png;base64,)
  • 将纯Base64字符串解码为字节数组
  • 将字节数组写入目标文件

完整代码示例:

using System;
using System.IO;

namespace Base64ImageSaver
{
    class Program
    {
        static void Main(string[] args)
        {
            string base64Image = "你的图片Base64字符串";
            string savePath = "cat-1285634_960_720.png";

            // 移除Base64前缀(如果存在)
            if (base64Image.StartsWith("data:image/", StringComparison.OrdinalIgnoreCase))
            {
                int commaIndex = base64Image.IndexOf(',') + 1;
                base64Image = base64Image.Substring(commaIndex);
            }

            try
            {
                byte[] imageBytes = Convert.FromBase64String(base64Image);
                File.WriteAllBytes(savePath, imageBytes);
                Console.WriteLine($"图片已保存至:{Path.GetFullPath(savePath)}");
            }
            catch (FormatException)
            {
                Console.WriteLine("无效的Base64字符串格式");
            }
            catch (IOException ex)
            {
                Console.WriteLine($"保存失败:{ex.Message}");
            }
        }
    }
}

补充说明:

如果你的场景必须处理图片(如缩放、格式转换),可以通过NuGet安装System.Drawing.Common包,但注意该包在.NET 6+的非Windows平台已被标记为过时,仅推荐Windows环境使用。直接写入字节数组的方式无需额外依赖,更适合单纯的保存需求。

内容的提问来源于stack exchange,提问作者chobo2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:01:46