判断文件格式
判断文件格式,以便处理:
if UpperCase(ExtractFileExt(sFileName)) <> '.PDF' then
begin
imgCapture.Picture.Graphic := nil;
imgCapture.Picture.LoadFromFile(sFileName);
end;
unit SysUtils;
function ExtractFileName(const FileName: string): string;//返回文件名
var
I: Integer;
begin
I := LastDelimiter(PathDelim + DriveDelim, FileName);
Result := Copy(FileName, I + 1, MaxInt);
end;
function ExtractFileExt(const FileName: string): string;//返回文件后缀名
var
I: Integer;
begin
I := LastDelimiter('.' + PathDelim + DriveDelim, FileName);
if (I > 0) and (FileName[I] = '.') then
Result := Copy(FileName, I, MaxInt) else
Result := '';
end;
{-------------------------------------------------------------------------------
过程名: isBmpFile
参 数: AFileName:完整的文件名称
功 能: 判断图片是不是合法的BMP格式
返回值: TRUE:是bmp图片文件;FALSE 不是bmp图片文件。
-------------------------------------------------------------------------------}
function isBmpFile(const AFileName: string): Boolean;
const
RightBuf: array[0..1] of Byte = ($42, $4D);
var
Buf: array[0..1] of Byte;
begin
FillChar(Buf, 2, 0);
with TFileStream.Create(AFileName, fmOpenRead) do
begin
Position := 0;
Read(Buf[0], 2);
Free;
end;
Result := CompareMem(@RightBuf[0], @Buf[0], 2);
end;
{说明同上}
function isJpgFile(const AFileName: string): Boolean;
const
RightBuf: array[0..3] of Byte = ($FF, $D8, $FF, $D9);
var
Buf: array[0..3] of Byte;
begin
FillChar(Buf, 4, 0);
with TFileStream.Create(AFileName, fmOpenRead) do
begin
Position := 0;
Read(Buf[0], 2);
Position := Size - 2;
Read(Buf[2], 2);
Free;
end;
Result := CompareMem(@RightBuf[0], @Buf[0], 4);
end;
{说明同上}
function isPngFile(const AFileName: string): Boolean;
const
RightBuf: array[0..3] of Byte = ($89, $50, $60, $82);
var
Buf: array[0..3] of Byte;
begin
FillChar(Buf, 4, 0);
with TFileStream.Create(AFileName, fmOpenRead) do
begin
Position := 0;
Read(Buf[0], 2);
Position := Size - 2;
Read(Buf[2], 2);
Free;
end;
Result := CompareMem(@RightBuf[0], @Buf[0], 4);
end;
{加载文件}
function ImgLoadfromFile(AImge: TImage; AFileName: string): Boolean;
var
BitMap: TBitmap;
jpg: TJPEGImage;
FsStram: TMemoryStream;
PngObj: TPNGObject;
begin
Result := False;
try
FsStram := TMemoryStream.Create;
FsStram.LoadFromFile(AFileName);
if FsStram.Size = 0 then
Exit;
FsStram.Seek(0, soFromBeginning);
if isBmpFile(AFileName) then
begin
try
BitMap := TBitmap.Create;
BitMap.LoadFromStream(FsStram);
AImge.Picture.Assign(BitMap);
AImge.Picture.Graphic.Modified := True;
Result := True;
finally
BitMap.Free;
end;
end
else if isJpgFile(AFileName) then
begin
try
jpg := TJPEGImage.Create;
jpg.LoadFromStream(FsStram);
AImge.Picture.Assign(jpg);
AImge.Picture.Graphic.Modified := True;
Result := True;
finally
jpg.Free;
end;
end
else if isPngFile(AFileName) then
begin
try
PngObj := TPNGObject.Create;
PngObj.LoadFromStream(FsStram);
AImge.Picture.Assign(PngObj);
AImge.Picture.Graphic.Modified := True;
Result := True;
finally
PngObj.Free;
end;
end;
finally
FsStram.Free;
end;
end;