我写过一个从文件中提取多张图象的程序,是使用流来处理,你可以参考下。
TCheckImageFile = class(TObject)
private
FRoomSize: Int64;//一副图片固定空间大小10k
FFileStream: TFileStream;//用来存放文件
FList: TObjectList; //用来表示图象对象列表
FFileName: String;
function GetItem(Index: Integer): TJPEGImage;
procedure CopyImageToItem(BeginPosition,AFileSize: Int64);
function GetCount: integer;
protected
procedure DistillImage;//提取图象
public
constructor Create(const FileName: string);
destructor Destroy; override;
property FileName: String read FFileName;
property Count: integer read GetCount;
property Items[index: integer]: TJPEGImage read GetItem;
end;
procedure TCheckImageFile.CopyImageToItem(BeginPosition, AFileSize: Int64);
var
Image: TJPEGImage;
stream: TMemoryStream;
begin
if FFileStream.Position <> BeginPosition then
FFileStream.Seek(BeginPosition,soBeginning);
Image := TJPEGImage.Create;
stream := TMemoryStream.Create;
try
stream.CopyFrom(FFileStream,AFileSize);
stream.Seek(0,soFromBeginning);
Image.LoadFromStream(stream);
FList.Add(Image);
finally
stream.free;
end;
end;
constructor TCheckImageFile.Create(const FileName: string);
begin
FRoomSize := 10 * 1024 ;//10k图象
FFileStream := TFileStream.Create(FileName,fmOpenRead);
//if FFileStream = nil then RaiseError
FList := TObjectList.Create;
DistillImage;
end;
destructor TCheckImageFile.Destroy;
begin
if Assigned(FFileStream) then
FFileStream.Free;
FList.Free;
inherited Destroy;
end;
procedure TCheckImageFile.DistillImage;
var
CheckImage : TCheckImage;
nIndex: integer;
begin
//从文件流中提取出图象,保存到objectlist中
nIndex := 0;
if FFileStream.Size < 1 then exit;
FFileStream.Read(CheckImage,SizeOf(TCheckImage));
while CheckImage.FileSize > 0 do
begin
if CheckImage.FileSize > FRoomSize then
Exception.Create('Image File Size Out of '+ inttostr(FRoomSize));
CopyImageToItem(FFileStream.Position,CheckImage.FileSize-SizeOf(TCheckImage));
Inc(nIndex);
FFileStream.Seek((FRoomSize + SizeOf(TCheckImage)) * nIndex ,soBeginning);
if FFileStream.Position >= FFileStream.Size then break;
FFileStream.Read(CheckImage,SizeOf(TCheckImage));
end;
end;
function TCheckImageFile.GetCount: integer;
begin
result := FList.Count;
end;
function TCheckImageFile.GetItem(Index: Integer): TJPEGImage;
begin
result := nil;
if (Index < 0) or (Index > FList.Count - 1) then
exit;
result := TJPEGImage(FList.Items[Index]);
end;