d2phap/ImageGlass · error · FormatException
The base64 content is invalid.
Error message
The base64 content is invalid.
What it means
Thrown by MagickCodec.ConvertBase64ToBytes when the input string does not match the base64 data-URI regex. The regex (source-generated, case-insensitive) is anchored with ^...$ and requires an optional 'data:image/<subtype>;base64,' prefix followed by one or more characters from [A-Za-z0-9+/=] only. A null/blank value is rejected earlier with ArgumentNullException; this FormatException means the string had content but was not well-formed base64.
Source
Thrown at source/ImageGlass.Lib/Common/Photoing/Codecs/MagickCodecs/MagickCodec.cs:693
/// <summary>
/// Converts base64 string to byte array, returns MIME type and raw data in byte array.
/// </summary>
public static (string MimeType, byte[] ByteData) ConvertBase64ToBytes(string? content)
{
if (string.IsNullOrWhiteSpace(content))
{
throw new ArgumentNullException(nameof(content));
}
// data:image/svg-xml;base64,xxxxxxxx
// type is optional
var base64DataUriRegex = CreateBase64DataUriRegex__();
var match = base64DataUriRegex.Match(content);
if (!match.Success)
{
throw new FormatException("The base64 content is invalid.");
}
var base64Data = match.Groups["data"].Value;
var byteData = Convert.FromBase64String(base64Data);
var mimeType = match.Groups["type"].Value.ToLowerInvariant();
if (mimeType.Length == 0)
{
// use default PNG MIME type
mimeType = "image/png";
}
return (mimeType, byteData);
}
/// <summary>View on GitHub (pinned to 4a3c4fecef)
Solutions
- Strip all whitespace and newlines from the string before calling: content = Regex.Replace(content, @"\s+", "").
- If the source is URL-safe base64, map it back: content = content.Replace('-','+').Replace('_','/'); then re-pad to a multiple of 4 with '='.
- Verify the data-URI prefix matches 'data:image/<subtype>;base64,' exactly (lowercase 'image/', semicolon, 'base64,', comma).
- Pre-validate with Convert.FromBase64String in a try/catch on the data portion to get a clearer error before calling this API.
Example fix
// before
var (mime, bytes) = MagickCodec.ConvertBase64ToBytes(raw);
// after
var cleaned = Regex.Replace(raw ?? string.Empty, @"\s+", "")
.Replace('-', '+').Replace('_', '/');
var pad = (4 - cleaned.Length % 4) % 4;
cleaned = cleaned.PadRight(cleaned.Length + pad, '=');
var (mime, bytes) = MagickCodec.ConvertBase64ToBytes(cleaned); Defensive patterns
Strategy: validation
Validate before calling
static bool IsValidBase64DataUri(string? content)
{
if (string.IsNullOrWhiteSpace(content)) return false;
var cleaned = Regex.Replace(content, @"\s+", "");
// strip optional data-uri prefix
var comma = cleaned.IndexOf(',');
if (comma >= 0 && cleaned.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
cleaned = cleaned[(comma + 1)..];
var pad = (4 - cleaned.Length % 4) % 4;
cleaned = cleaned.PadRight(cleaned.Length + pad, '=');
return Regex.IsMatch(cleaned, @"^[A-Za-z0-9+/]+={0,2}$");
} Try / catch
try { var (mime, bytes) = MagickCodec.ConvertBase64ToBytes(content); }
catch (FormatException ex) when (ex.Message.Contains("base64 content is invalid"))
{ /* log and reject the input */ } Prevention
- Always strip whitespace/newlines from base64 input before calling.
- Convert URL-safe base64 (- and _) back to standard (+ and /) and re-pad.
- Pre-validate with Convert.FromBase64String in a try/catch to get a clearer error.
When it happens
Trigger: Calling ConvertBase64ToBytes with: a string containing embedded whitespace or newlines inside the data; URL-safe base64 using '-' or '_' instead of '+' or '/'; base64 missing its '=' padding; a malformed data-URI prefix (wrong mime token, missing semicolon/comma); or any non-base64 text. The trailing '$' anchor makes a single stray character fail the whole match.
Common situations: Pasting base64 copied from a browser dev-tools panel or file that wrapped long lines; receiving URL-safe base64 from a JWT/web library; reading a data URI from a config file that picked up a trailing CR/LF; clipboard content with a leading/trailing space.
Related errors
- IGE: Unsupported image format.
- IGE_002
- IGE: Unsupported image format.
- The base64 content is invalid.
- IGE: '{codec.CodecName}' could not write the image. {result.
AI-assisted analysis of d2phap/ImageGlass@4a3c4fecef (2026-08-13).
Data as JSON: /api/errors/1040a66d8a0684e1.
Report an issue: GitHub.