Как можно закодировать картинку в base64 на Delphi?
3 ответа
Если вас интересует вопрос как перевести байты в base64 строку, то в интернете полно вариантов реализаций. Правда, многие из них с ошибками :) Вот мой работающий вариант:
function EncodeBase64(const Input: TBytes): string;
const
Base64: array[0..63] of Char =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function Encode3Bytes(const Byte1, Byte2, Byte3: Byte): string;
begin
Result := Base64[Byte1 shr 2]
+ Base64[((Byte1 shl 4) or (Byte2 shr 4)) and $3F]
+ Base64[((Byte2 shl 2) or (Byte3 shr 6)) and $3F]
+ Base64[Byte3 and $3F];
end;
function EncodeLast2Bytes(const Byte1, Byte2: Byte): string;
begin
Result := Base64[Byte1 shr 2]
+ Base64[((Byte1 shl 4) or (Byte2 shr 4)) and $3F]
+ Base64[(Byte2 shl 2) and $3F] + '=';
end;
function EncodeLast1Byte(const Byte1: Byte): string;
begin
Result := Base64[Byte1 shr 2]
+ Base64[(Byte1 shl 4) and $3F] + '==';
end;
var
i, iLength: Integer;
begin
Result := '';
iLength := Length(Input);
i := 0;
while i < iLength do
begin
case iLength - i of
3..MaxInt:
Result := Result + Encode3Bytes(Input[i], Input[i+1], Input[i+2]);
2:
Result := Result + EncodeLast2Bytes(Input[i], Input[i+1]);
1:
Result := Result + EncodeLast1Byte(Input[i]);
end;
Inc(i, 3);
end;
end;
Бывают различия в кодировании последних 2-х или одного байта (когда число байт не делится без остатка на 3). Уточняйте как их вам нужно закодировать.
Если вас интересует как из картинки получить байты, то для этого есть много способов. Создайте отдельный вопрос и уточняйте там условия.
Я проверил несколько функций, самая быстрая из них из библиотеки Sha_Strings,
можно почитать здесь http://www.delphimaster.net/view/15-1163507354/0-39
Если есть установленные компоненты Indy - можно воспользоваться функционалом, который есть в модуле idGlobal:
uses
idGlobal;
function DecodeBase64(const AText: string): string;
begin
Result := TIdDecoderMIME.DecodeString(AText);
end;
function EncodeBase64(const AText: string): string;
begin
Result := TIdEncoderMIME.EncodeString(AText);
end;