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

C#.NET4.7类库中Base64转Bitmap绘多边形遇长度错误求助

解决.NET 4.7类库中带头部Base64转Bitmap的错误及绘制多边形方案

我之前在.NET 4.7类库开发中碰到过一模一样的问题,这个Invalid length for a Base-64 char array or string错误本质是因为你直接传入了带数据URI头部的Base64字符串——.NET的Convert.FromBase64String根本不认识data:image/xxx;base64,这种前缀,而且Base64要求字符串长度必须是4的倍数,前缀的存在直接打破了这个规则,自然就报错了。

下面是完整的解决方案,包含Base64转Bitmap的修复逻辑,以及在Bitmap上绘制多边形的实现:

1. 先清理带头部的Base64字符串

第一步必须剥离Base64中的数据URI头部,同时修复字符串长度确保符合Base64的格式要求(长度为4的倍数,不足时补=):

private static string CleanBase64String(string base64WithHeader)
{
    // 剥离data URI头部(比如data:image/png;base64,)
    if (base64WithHeader.StartsWith("data:image/", StringComparison.OrdinalIgnoreCase))
    {
        int headerEndIndex = base64WithHeader.IndexOf(";base64,", StringComparison.OrdinalIgnoreCase);
        if (headerEndIndex != -1)
        {
            base64WithHeader = base64WithHeader.Substring(headerEndIndex + 8); // 8是";base64,"的字符长度
        }
    }

    // 去除可能存在的换行、空格等干扰字符
    base64WithHeader = base64WithHeader.Replace("\r", "").Replace("\n", "").Trim();

    // 修复Base64长度,确保是4的倍数
    int padding = base64WithHeader.Length % 4;
    if (padding != 0)
    {
        base64WithHeader += new string('=', 4 - padding);
    }

    return base64WithHeader;
}

2. 转换清理后的Base64为Bitmap

使用MemoryStream处理字节数组,注意返回新的Bitmap对象避免流关闭后原Bitmap失效:

private static Bitmap ConvertBase64ToBitmap(string cleanBase64)
{
    byte[] imageBytes = Convert.FromBase64String(cleanBase64);
    using (MemoryStream ms = new MemoryStream(imageBytes))
    {
        // 先加载为Bitmap,再返回新实例,避免流关闭后Bitmap无法使用
        using (Bitmap tempBitmap = new Bitmap(ms))
        {
            return new Bitmap(tempBitmap);
        }
    }
}

3. 在Bitmap上绘制多边形

通过Graphics类实现多边形的描边和填充,支持自定义颜色、线条宽度等:

private static void DrawPolygonOnBitmap(Bitmap bitmap, Point[] polygonPoints)
{
    using (Graphics g = Graphics.FromImage(bitmap))
    {
        // 设置高质量绘制参数
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

        // 绘制多边形边框(红色,线条宽度2)
        using (Pen pen = new Pen(Color.Red, 2))
        {
            g.DrawPolygon(pen, polygonPoints);
        }

        // 可选:填充多边形内部(半透明蓝色)
        using (Brush brush = new SolidBrush(Color.FromArgb(100, Color.Blue)))
        {
            g.FillPolygon(brush, polygonPoints);
        }
    }
}

4. 完整调用示例

把上述方法整合,处理你的Base64字符串和像素坐标:

// 替换为你的带头部Base64字符串
string base64WithHeader = "你的带头部Base64内容";
// 替换为你的四个像素坐标
Point[] polygonPoints = new Point[]
{
    new Point(50, 50),
    new Point(200, 50),
    new Point(200, 200),
    new Point(50, 200)
};

try
{
    string cleanBase64 = CleanBase64String(base64WithHeader);
    Bitmap bitmap = ConvertBase64ToBitmap(cleanBase64);
    DrawPolygonOnBitmap(bitmap, polygonPoints);

    // 保存处理后的图片,或根据业务需求返回Bitmap对象
    bitmap.Save("processed_image.png", System.Drawing.Imaging.ImageFormat.Png);
    
    // 记得手动释放Bitmap资源
    bitmap.Dispose();
}
catch (Exception ex)
{
    // 捕获并处理异常(比如Base64损坏、不支持的图片格式等)
    Console.WriteLine($"处理失败:{ex.Message}");
}

额外排查点

如果清理后仍报错,可以检查:

  • Base64字符串本身是否损坏(比如传输过程中丢失字符)
  • 图片格式是否为.NET Bitmap支持的类型(如PNG、JPG、BMP,不支持WebP等小众格式)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:53:19