-
Notifications
You must be signed in to change notification settings - Fork 58
/
OpenAI.Utils.Base64.pas
67 lines (56 loc) · 1.52 KB
/
OpenAI.Utils.Base64.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
unit OpenAI.Utils.Base64;
interface
uses
System.SysUtils, System.NetEncoding, System.Classes, System.Net.Mime,
OpenAI.Types;
function FileToBase64(const FileName: TFileName): TBase64Data;
function StreamToBase64(Stream: TStream; const ContentType: string): TBase64Data;
function GetFileContentType(const FileName: TFileName): string;
implementation
function GetFileContentType(const FileName: TFileName): string;
var
LKind: TMimeTypes.TKind;
begin
TMimeTypes.Default.GetFileInfo(FileName, Result, LKind);
end;
function FileToBase64(const FileName: TFileName): TBase64Data;
var
FS: TFileStream;
Base64: TStringStream;
begin
FS := TFileStream.Create(FileName, fmOpenRead);
try
Base64 := TStringStream.Create('', TEncoding.UTF8);
try
{$IF RTLVersion >= 35.0}
TNetEncoding.Base64String.Encode(FS, Base64);
{$ELSE}
TNetEncoding.Base64.Encode(FS, Base64);
{$ENDIF}
Result.Data := Base64.DataString;
Result.ContentType := GetFileContentType(FileName);
finally
Base64.Free;
end;
finally
FS.Free;
end;
end;
function StreamToBase64(Stream: TStream; const ContentType: string): TBase64Data;
var
Base64: TStringStream;
begin
Base64 := TStringStream.Create('', TEncoding.UTF8);
try
{$IF RTLVersion >= 35.0}
TNetEncoding.Base64String.Encode(Stream, Base64);
{$ELSE}
TNetEncoding.Base64.Encode(Stream, Base64);
{$ENDIF}
Result.Data := Base64.DataString;
Result.ContentType := ContentType;
finally
Base64.Free;
end;
end;
end.