{"record":{"id":"1040a66d8a0684e1","repo":"d2phap/ImageGlass","slug":"the-base64-content-is-invalid","errorCode":null,"errorMessage":"The base64 content is invalid.","messagePattern":"The base64 content is invalid\\.","errorType":"exception","errorClass":"FormatException","httpStatus":null,"severity":"error","filePath":"source/ImageGlass.Lib/Common/Photoing/Codecs/MagickCodecs/MagickCodec.cs","lineNumber":693,"sourceCode":"\n    /// <summary>\n    /// Converts base64 string to byte array, returns MIME type and raw data in byte array.\n    /// </summary>\n    public static (string MimeType, byte[] ByteData) ConvertBase64ToBytes(string? content)\n    {\n        if (string.IsNullOrWhiteSpace(content))\n        {\n            throw new ArgumentNullException(nameof(content));\n        }\n\n        // data:image/svg-xml;base64,xxxxxxxx\n        // type is optional\n        var base64DataUriRegex = CreateBase64DataUriRegex__();\n        var match = base64DataUriRegex.Match(content);\n\n        if (!match.Success)\n        {\n            throw new FormatException(\"The base64 content is invalid.\");\n        }\n\n\n        var base64Data = match.Groups[\"data\"].Value;\n        var byteData = Convert.FromBase64String(base64Data);\n        var mimeType = match.Groups[\"type\"].Value.ToLowerInvariant();\n\n        if (mimeType.Length == 0)\n        {\n            // use default PNG MIME type\n            mimeType = \"image/png\";\n        }\n\n        return (mimeType, byteData);\n    }\n\n\n    /// <summary>","sourceCodeStart":675,"sourceCodeEnd":711,"githubUrl":"https://github.com/d2phap/ImageGlass/blob/4a3c4feceffc5a8bb5e56ba836509634aaae47a9/source/ImageGlass.Lib/Common/Photoing/Codecs/MagickCodecs/MagickCodec.cs#L675-L711","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"// before\nvar (mime, bytes) = MagickCodec.ConvertBase64ToBytes(raw);\n\n// after\nvar cleaned = Regex.Replace(raw ?? string.Empty, @\"\\s+\", \"\")\n                   .Replace('-', '+').Replace('_', '/');\nvar pad = (4 - cleaned.Length % 4) % 4;\ncleaned = cleaned.PadRight(cleaned.Length + pad, '=');\nvar (mime, bytes) = MagickCodec.ConvertBase64ToBytes(cleaned);","handlingStrategy":"validation","validationCode":"static bool IsValidBase64DataUri(string? content)\n{\n    if (string.IsNullOrWhiteSpace(content)) return false;\n    var cleaned = Regex.Replace(content, @\"\\s+\", \"\");\n    // strip optional data-uri prefix\n    var comma = cleaned.IndexOf(',');\n    if (comma >= 0 && cleaned.StartsWith(\"data:\", StringComparison.OrdinalIgnoreCase))\n        cleaned = cleaned[(comma + 1)..];\n    var pad = (4 - cleaned.Length % 4) % 4;\n    cleaned = cleaned.PadRight(cleaned.Length + pad, '=');\n    return Regex.IsMatch(cleaned, @\"^[A-Za-z0-9+/]+={0,2}$\");\n}","typeGuard":null,"tryCatchPattern":"try { var (mime, bytes) = MagickCodec.ConvertBase64ToBytes(content); }\ncatch (FormatException ex) when (ex.Message.Contains(\"base64 content is invalid\"))\n{ /* log and reject the input */ }","preventionTips":["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."],"tags":["base64","codec","magick","format","data-uri"],"backgroundTag":null,"analyzedSha":"4a3c4feceffc5a8bb5e56ba836509634aaae47a9","analyzedAt":"2026-08-13T16:58:15.523Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}