uses jpeg,EncdDecd,ZLibEx
//字符串base64 编码
Function StrtoBase64(const Str:string):string;
begin
result:=EncodeString(Str);
end;
//字符串base64 解码
Function Base64toStr(const Base64:string):string;
begin
result:=DecodeString(base64);
end;
//Jpeg base64 编码
Function JpegToBase64(Jpeg : Tjpegimage):string;
var
jpegstream : TMemoryStream;
StrStream : TStringStream;
begin
jpegstream :=TMemoryStream.Create;
StrStream :=TStringStream.Create('');
jpeg.SaveToStream(jpegstream);
jpegstream.Position:=0;
EncodeStream(Jpegstream,strstream);
result:=strstream.DataString;
jpegstream.Free;
strstream.Free;
end;
//Jpeg base64 解码
Function Base64ToJpeg(str: string):TJpegimage;
var
jpegstream : TMemoryStream;
StrStream : TStringStream;
begin
jpegstream :=TMemoryStream.Create;
StrStream :=TStringStream.Create(str);
DecodeStream(StrStream,JpegStream);
JpegStream.Position:=0;
result:=TJpegimage.Create;
result.LoadFromStream(JpegStream);
jpegstream.Free;
strstream.Free;
end;
///将Bitmap位图转化为base64字符串
function BitmapToString(img:TBitmap):string ;
var
ms:TMemoryStream;
ss:TStringStream;
s:string;
begin
ms := TMemoryStream.Create;
img.SaveToStream(ms);
ss := TStringStream.Create('');
ms.Position:=0;
EncodeStream(ms,ss);//将内存流编码为base64字符流
s:=ss.DataString;
ms.Free;
ss.Free;
result:=s;
end;
///将base64字符串转化为Bitmap位图
function StringToBitmap(imgStr:string):TBitmap;
var ss:TStringStream;
ms:TMemoryStream;
bitmap:TBitmap;
begin
ss := TStringStream.Create(imgStr);
ms := TMemoryStream.Create;
DecodeStream(ss,ms);//将base64字符流还原为内存流
ms.Position:=0;
bitmap := TBitmap.Create;
bitmap.LoadFromStream(ms);
ss.Free;
ms.Free;
result :=bitmap;
end;
function CompressStrToBase64(sStr: string): string;
var
M1: TMemoryStream;
M0, M2: TStringStream;
begin
Result := '';
if sStr = '' then
Exit;
M0 := TStringStream.Create(sStr);
M1 := TMemoryStream.Create;
M2 := TStringStream.Create(' ');
try
M0.Position := 0;
M1.Position := 0;
ZCompressStream(M0, M1);
M1.Position := 0;
M2.Position := 0;
EncodeStream(M1, M2);
Result := M2.DataString;
finally
FreeAndNil(M0);
FreeAndNil(M1);
FreeAndNil(M2);
end;
end;
function DeCompressBase64ToStr(sStr: string): string;
var
M0, M1: TStringStream;
M2: TMemoryStream;
begin
Result := '';
if sStr = '' then
Exit;
M0 := TStringStream.Create;
M1 := TStringStream.Create(sStr);
M2 := TMemoryStream.Create;
try
M1.Position := 0;
M2.Position := 0;
DeCodeStream(M1, M2);
M0.Position := 0;
M2.Position := 0;
ZDecompressStream(M2, M0);
Result := M0.DataString;
finally
FreeAndNil(M0);
FreeAndNil(M2);
FreeAndNil(M1);
end;
end;