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;
  • 相关阅读:
    商品详情的图片添加水印
    ElasticSearch 简单的crud查询
    java产生随机数的三种方式
    springboot+mybatis集成分页功能
    springboot集成swagger文档
    springboot项目根据不同的环境启动不同的配置,如开发环境dev,测试环境sit,生产环境application
    解释器模式
    中介者模式
    访问者模式
    x01.FileProcessor: 文件处理
  • 原文地址:https://www.cnblogs.com/railgunman/p/1889725.html
Copyright © 2011-2022 走看看