zoukankan      html  css  js  c++  java
  • 二进制文件转成文本保存,并可以读回

    以 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;
  • 相关阅读:
    “软件工程”课程评价
    我爱淘二次冲刺阶段4
    我爱淘二次冲刺阶段3
    我爱淘二次冲刺阶段2
    MVC框架具体使用
    初次见面- MVC
    设计模式
    读大型网站技术架构后感
    以《淘宝以《淘宝网》为例,描绘质量属性的六个常见属性场景。
    以《淘宝网》为例,描绘质量属性的六个常见属性场景。
  • 原文地址:https://www.cnblogs.com/railgunman/p/1889725.html
Copyright © 2011-2022 走看看