Skip to content

Decodificação

Antônio José Medeiros Schneider Jr. edited this page Aug 28, 2024 · 4 revisions

O processo de decodificação do formato Base64, é o processo inverso da codificação, é a conversão da string Base64 de volta para os dados binários originais.

Uso da biblioteca

Uses
  Base64Lib;

Base64 >> Text

var
  lDecode: IDecodeParse;
  lText: string;
  lSize: Int64;
  lMD5: string;
begin
  lDecode := TBase64Lib
    .Build
      .Decode
        .Text('QmFzZTY0TGli');

  if not Assigned(lDecode) then
    Exit;

  lText := lDecode.AsString;
  lSize := lDecode.Size;
  lMD5 := lDecode.MD5;
end;

Base64 >> Stream

var
  lBase64Stream: TStringStream;
  lResultStream: TStringStream;
  lDecode: IDecodeParse;
  lSize: Int64;
  lMD5: string;
begin
  lBase64Stream := TStringStream.Create('QmFzZTY0TGli', TEncoding.UTF8);

  lDecode := TBase64Lib
    .Build
      .Decode
        .Stream(lBase64Stream, True);

  if not Assigned(lDecode) then
    Exit;

  lResultStream := TStringStream.Create('', TEncoding.UTF8);
  lResultStream.CopyFrom(lDecode.AsStream);

  lSize := lDecode.Size;
  lMD5 := lDecode.MD5;
end;

Base64 >> File

var
  lDecode: IDecodeParse;
  lText: string;
  lSize: Int64;
  lMD5: string;
begin
  lDecode := TBase64Lib
    .Build
      .Decode
        .&File('C:\Base64.txt');
  
  if not Assigned(lDecode) then
    Exit;
  
  lText := lDecode.AsString;
  lSize := lDecode.Size;
  lMD5 := lDecode.MD5;
end;

Base64 >> Image

VCL

var
  lDecode: IDecodeParse;
  lPicture: TPicture;
  lSize: Int64;
  lMD5: string;
begin
  lDecode := TBase64Lib
    .Build
      .Decode
        .Text('QmFzZTY0TGli');

  if not Assigned(lDecode) then
    Exit;

  lPicture := lDecode.AsPicture;
  try   
    Image1.Picture.Assign(nil);
    Image1.Picture.Assign(lPicture);
  finally
    lPicture.Free;
  end;

  lSize := lDecode.Size;
  lMD5 := lDecode.MD5;
end;

FMX

var
  lDecode: IDecodeParse;
  lBitmapStream: TStream;
  lBitmap: TBitmap;
  lItem: TCustomBitmapItem; // FMX - Unit FMX.MultiResBitmap
  lRect: TRect; // FMX
  lSize: Int64;
  lMD5: string;
begin
  lDecode := TBase64Lib
    .Build
      .Decode
        .Text('QmFzZTY0TGli');

  if not Assigned(lDecode) then
    Exit;

  lBitmap := lDecode.AsBitmap;
  try
    lRect := TRect.Create(TPoint.Zero);
    lRect.Left := 0;
    lRect.Top := 0;
    lRect.Width := lBitmap.Bounds.Width;
    lRect.Height := lBitmap.Bounds.Height;

    Image1.MultiResBitmap.Clear;
    lItem := Image1.MultiResBitmap.ItemByScale(1, False, True);
    lItem.Bitmap.Width := lBitmap.Bounds.Width;
    lItem.Bitmap.Height  := lBitmap.Bounds.Height;
    lItem.Bitmap.CopyFromBitmap(lBitmap, lRect, 0, 0);
  finally
    lBitmap.Free;
  end;

  OU

  lBitmapStream := lDecode.AsStream;
  try
    Image1.MultiResBitmap.Clear;
    lItem := Image1.MultiResBitmap.ItemByScale(1, False, True);
    lItem.Bitmap.LoadFromStream(lBitmapStream);
  finally
    lBitmapStream.Free;
  end;

  lSize := lDecode.Size;
  lMD5 := lDecode.MD5;
end;

⬆️