首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi TStream 串流操作全攻略:檔案、記憶體、Blob 互讀寫實戰

     編輯:Delphi

TStream 是 VCL 統一抽象的串流基類,封裝了檔案、記憶體、資料庫 Blob、OLE 物件等各種資料來源的讀寫與定位操作。掌握 TStream 及其常用子類(TFileStream、TMemoryStream、TBlobStream),即可在檔案系統、記憶體、資料庫間自由搬移二進位資料(圖片、文件、序列化物件),是進階 Delphi 開發必備技能。

核心方法與屬性速查

成員說明
Read(var Buffer; Count): Longint從串流讀 Count 位元組到 Buffer,回傳實際讀取位元組數
Write(const Buffer; Count): Longint從 Buffer 寫 Count 位元組到串流,回傳實際寫入位元組數
Seek(Offset, Origin): Longint移動指標:Origin = soFromBeginning/soFromCurrent/soFromEnd
Position目前指標位置(可讀寫,內部呼叫 Seek)
Size串流總大小(部分串流唯讀)
SaveToStream(Stream) / LoadFromStream(Stream)VCL 物件(Bitmap、StringList 等)通用的序列化/反序列化方法

三大常用串流實戰範例

1. TFileStream:圖片檔 ⇄ Bitmap 控件

// 讀檔案到 Image1
var FS: TFileStream;
begin
  if OpenDialog1.Execute then begin
    FS := TFileStream.Create(OpenDialog1.FileName, fmOpenRead);
    try
      Image1.Picture.Bitmap.LoadFromStream(FS);
    finally
      FS.Free;
    end;
  end;
end;

2. TMemoryStream:記憶體圖片反色處理

var MS: TMemoryStream; P: Pointer;
begin
  MS := TMemoryStream.Create;
  try
    Image1.Picture.Bitmap.SaveToStream(MS); // 存入記憶體
    MS.Position := 0;
    P := Invert(MS.Memory, MS.Size);        // 自定義像素處理函數
    MS.Write(P^, MS.Size);                  // 寫回串流
    MS.Position := 0;
    Image1.Picture.Bitmap.LoadFromStream(MS); // 顯示結果
    FreeMem(P);
  finally
    MS.Free;
  end;
end;

3. TBlobStream:資料庫 Blob 欄位 ⇄ 圖片

// 存入資料庫
var MS: TMemoryStream;
begin
  MS := TMemoryStream.Create;
  try
    Image1.Picture.Bitmap.SaveToStream(MS);
    MS.Position := 0;
    Table1.Append;
    TBlobField(Table1.FieldByName('Image')).LoadFromStream(MS);
    Table1.Post;
  finally
    MS.Free;
  end;
end;

// 從資料庫讀出
var BS: TStream;
begin
  BS := Table1.CreateBlobStream(Table1.FieldByName('Image'), bmRead);
  try
    Image1.Picture.Bitmap.LoadFromStream(BS);
  finally
    BS.Free;
  end;
end;

關鍵提醒

  • 串流操作前後務必 Position := 0 歸零,否則讀寫位置錯誤導致資料損壞。
  • 記憶體串流處理大檔案需注意記憶體壓力,大檔案建議分塊或直接用 TFileStream。
  • TBlobStream 必須在 Dataset 開啟且處於編輯/瀏覽狀態下建立,用完即釋放。
  • 所有串流物件嚴格遵循 try...finally Free 模式防止洩漏。

掌握 TStream 體系,你就擁有了在任何二進位資料源之間「任意門」般的搬運能力。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved