openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
OpenAI/src/Utility/DataEncodingHelpers.cs
42lines · modecode
| 1 | using System; |
| 2 | using System.Text.RegularExpressions; |
| 3 | |
| 4 | #nullable enable |
| 5 | |
| 6 | namespace OpenAI; |
| 7 | |
| 8 | internal static partial class DataEncodingHelpers |
| 9 | { |
| 10 | #if NET8_0_OR_GREATER |
| 11 | [GeneratedRegex(@"^data:(?<type>.+?);base64,(?<data>.+)$")] |
| 12 | private static partial Regex ParseDataUriRegex(); |
| 13 | #else |
| 14 | private static Regex ParseDataUriRegex() => s_parseDataUriRegex; |
| 15 | private static readonly Regex s_parseDataUriRegex = new(@"^data:(?<type>.+?);base64,(?<data>.+)$", RegexOptions.Compiled); |
| 16 | #endif |
| 17 | |
| 18 | public static bool TryParseDataUri(string dataUri, out BinaryData? bytes, out string? bytesMediaType) |
| 19 | { |
| 20 | Match parsedDataUri = ParseDataUriRegex().Match(dataUri); |
| 21 | |
| 22 | if (!parsedDataUri.Success) |
| 23 | { |
| 24 | bytes = null; |
| 25 | bytesMediaType = null; |
| 26 | return false; |
| 27 | } |
| 28 | |
| 29 | string matchedBase64Data = parsedDataUri.Groups["data"].Value; |
| 30 | byte[] matchedBase64RawBytes = Convert.FromBase64String(matchedBase64Data); |
| 31 | |
| 32 | bytes = BinaryData.FromBytes(matchedBase64RawBytes); |
| 33 | bytesMediaType = parsedDataUri.Groups["type"].Value; |
| 34 | return true; |
| 35 | } |
| 36 | |
| 37 | public static string CreateDataUri(BinaryData bytes, string bytesMediaType) |
| 38 | { |
| 39 | string base64Bytes = Convert.ToBase64String(bytes.ToArray()); |
| 40 | return $"data:{bytesMediaType};base64,{base64Bytes}"; |
| 41 | } |
| 42 | } |