二进制文件转成文本保存,并可以读回
以 JPEG 图片为例,以下代码演示了如何将一个 JPEG 图片保存为纯文本形式,并将其以图片形式读回并显示。
保存 TXT:
function TForm1.JpegToText(AFileName:string; SaveFile: Boolean; TxtFileName: string): string; var FileStream : TFileStream; StringStream : TStringStream; FSize : integer; FileData : string; i : integer; DataStr : string; begin try FileStream := TFileStream.Create(OpenDialog1.FileName, fmOpenRead); StringStream := TStringStream.Create(EmptyStr); FSize := FileStream.Size; StringStream.CopyFrom(FileStream, FSize); FileData := StringStream.DataString; DataStr := EmptyStr; for i := 1 to Length(FileData) do begin DataStr := DataStr + InttoHex(Ord(FileData[i]), 2); end; Result := DataStr; if SaveFile then begin with TStringList.Create do begin Text := DataStr; SaveToFile(TxtFileName); Free; end; end; finally freeandnil(FileStream); freeandnil(StringStream); end; end;
从 TXT 读回 JPEG:
function TForm1.TextToJpeg(AFileName: string; SaveFile: Boolean; JpegFileName: string): TJPEGImage; var buf : array of Byte; DataLength : Integer; i : Integer; DataStr : string; ByteFile : file of byte; jpg : TJPEGImage; tmpFileName: string; begin with TStringList.Create do begin LoadFromFile(AFileName); DataStr := Text; Free; end; DataLength := Length(DataStr) div 2-1; SetLength(buf, DataLength); for i := 1 to DataLength do begin buf[i - 1] := StrToInt('$' + copy(DataStr, (i - 1) * 2 + 1, 2)); end; tmpFileName := ExtractFilePath(ParamStr(0))+'tmp.jpg'; AssignFile(ByteFile, tmpFileName); Rewrite(ByteFile); for i := 0 to DataLength - 1 do begin write(ByteFile, buf[i]); end; CloseFile(ByteFile); Result := TJPEGImage.Create; Result.LoadFromFile(tmpFileName); if SaveFile then Result.SaveToFile(JpegFileName); DeleteFile(tmpFileName); end;