delphi - 使用delphi 2007对base64进行编码和解码base64

标签 delphi encoding base64 decoding delphi-2007

我必须在旧的 Delphi 2007 上将字节数组编码为 Base64 字符串(并解码该字符串)。 我该怎么办?

更多信息:

我尝试过突触(如此处建议的 Binary to Base64 (Delphi) )。

最佳答案

Indy 随 Delphi 一起提供,并具有用于处理 base64 的 TIdEncoderMIMETIdDecoderMIME 类。例如:

uses
  ..., IdCoder, IdCoderMIME;

var
  Bytes: TIdBytes;
  Base64String: String;
begin
  //...
  Bytes := ...; // array of bytes
  //...
  Base64String := TIdEncoderMIME.EncodeBytes(Bytes);
  //...
  Bytes := TIdDecoderMIME.DecodeBytes(Base64String);
  //...
end;

还有用于编码/解码 StringTStream 数据的方法。

更新:或者,如果您的版本没有上面显示的 class 方法:

// TBytesStream was added in D2009, so define it manually for D2007

uses
  ..., IdCoder, IdCoderMIME
  {$IF RTLVersion < 20)
  , RTLConsts
  {$IFEND}
  ;

{$IF RTLVersion < 20)
type
  TBytesStream = class(TMemoryStream)
  private
    FBytes: TBytes;
  protected
    function Realloc(var NewCapacity: Longint): Pointer; override;
  public
    constructor Create(const ABytes: TBytes); overload;
    property Bytes: TBytes read FBytes;
  end;

constructor TBytesStream.Create(const ABytes: TBytes);
begin
  inherited Create;
  FBytes := ABytes;
  SetPointer(Pointer(FBytes), Length(FBytes));
  FCapacity := FSize;
end;

const
  MemoryDelta = $2000; // Must be a power of 2

function TBytesStream.Realloc(var NewCapacity: Integer): Pointer;
begin
  if (NewCapacity > 0) and (NewCapacity <> FSize) then
    NewCapacity := (NewCapacity + (MemoryDelta - 1)) and not (MemoryDelta - 1);
  Result := Pointer(FBytes);
  if NewCapacity <> FCapacity then
  begin
    SetLength(FBytes, NewCapacity);
    Result := Pointer(FBytes);
    if NewCapacity = 0 then
      Exit;
    if Result = nil then raise EStreamError.CreateRes(@SMemoryStreamError);
  end;
end;
{$IFEND}

var
  Bytes: TBytes;
  BStrm: TBytesStream;
  Encoder: TIdEncoderMIME;
  Decoder: TIdDecoderMIME;
  Base64String: String;
begin
  //...
  Bytes := ...; // array of bytes
  //...
  BStrm := TBytesStream.Create(Bytes);
  try
    Encoder := TIdEncoderMIME.Create;
    try
      Base64String := Encoder.Encode(BStrm);
    finally
      Encoder.Free;
    end;
  finally
    BStrm.Free;
  end;
  //...
  BStrm := TBytesStream.Create;
  try
    Decoder := TIdDecoderMIME.Create;
    try
      Decoder.DecodeBegin(BStrm);
      Decoder.Decode(Base64String);
      Decoder.DecodeEnd;
    finally
      Decoder.Free;
    end;
    Bytes := BStrm.Bytes;
  finally
    BStrm.Free;
  end;
  //...
end;

关于delphi - 使用delphi 2007对base64进行编码和解码base64,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30040382/

相关文章:

delphi - 根据拖动区域动态调整控件大小

Delphi 7 - ShellExecute 命令在某些情况下不起作用

objective-c - Converting Swift to Objective-C 解释编译器警告?

node.js - 如何检测 NodeJS 中的文件编码?

linux - 如何使用 bash 脚本从 base64 转换后的文件中播放声音?

c# - 如何将 Bitmap 转换为 Base64 字符串?

ios - Objective-c Base64 NSString 到 NSData 转换

delphi - Win3.1调色板中的控件更新

java - 如何通过 JDBC 访问 Windows 版 Blackfish?

python - 使用opencv和python将图像转换为值(例如十六进制代码)