Delphi里实现对图片Base64编码解码

5bug 2018-01-17 480人围观 ,发现0个评论 TIdEncoderMIMETIdDecoderMIMEBase64编码解码

前几天有个朋友问我这个问题:有段编码字符要转为图片,问我怎么实现?其实凭经验大多数人第一时间想到的就是这是base64编码,告知后但对方就是没法解,没办法啊,好人做到底,动手给对方写个demo,利用indy自带的TIdEncoderMIME和TIdDecoderMIME来完成该过程。关键代码如下:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, IdBaseComponent, IdCoder, IdCoder3to4, IdCoderMIME, IdGlobal,
  StdCtrls, ExtCtrls, jpeg, pngimage;

type
  TForm1 = class(TForm)
    IdEncoderMIME1: TIdEncoderMIME;
    Button1: TButton;
    IdDecoderMIME1: TIdDecoderMIME;
    Image1: TImage;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  LSrcStream, LDesStream: TMemoryStream;
  LPic: TPngImage;
begin
  LSrcStream := TMemoryStream.Create;
  try
    LDesStream := TMemoryStream.Create;
    try
      LSrcStream.LoadFromFile(ExtractFilePath(ParamStr(0)) + '1.txt');
      IdDecoderMIME1.DecodeBegin(LDesStream);
      IdDecoderMIME1.Decode(LSrcStream);
      IdDecoderMIME1.DecodeEnd;
      LDesStream.Position := 0;
      LPic := TPngImage.Create;
      try
        LPic.LoadFromStream(LDesStream);
        Image1.Picture.Assign(LPic);
      finally
        LPic.Free;
      end;
      LDesStream.SaveToFile(ExtractFilePath(ParamStr(0)) + '1.jpg');
    finally
      FreeAndNil(LDesStream);
    end;
  finally
    FreeAndNil(LSrcStream);
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  LSrcStream, LDesStream: TMemoryStream;
begin
  LSrcStream := TMemoryStream.Create;
  try
    LDesStream := TMemoryStream.Create;
    try
      LSrcStream.LoadFromFile(ExtractFilePath(ParamStr(0)) + '1.jpg');
      IdEncoderMIME1.Encode(LSrcStream, LDesStream);
      LDesStream.SaveToFile(ExtractFilePath(ParamStr(0)) + '1.txt');
    finally
      FreeAndNil(LDesStream);
    end;
  finally
    FreeAndNil(LSrcStream);
  end;
end;

end.

窗体文件就不贴了,遇到该问题的可以参考下,Delphi高版本里完成的!

不容错过
Powered By Z-BlogPHP