我必须从 XML 文件加载图像。 XML 文件中没有关于图像是否为 JPG/GIF/BMP 的信息。加载图像后,我需要将其转换为位图。
有人知道如何在不知道实际文件格式的情况下将图像转换为位图吗?我正在使用 Delphi 2007/2009
谢谢。
最佳答案
Delphi 2009 内置了对 JPEG、BMP、GIF 和 PNG 的支持。
对于早期版本的 Delphi,您可能需要找到 PNG 和 GIF 的第三方实现,但在 Delphi 2009 中,您只需添加 Jpeg
、pngimage
和 GIFImg
单位添加到您的 use 子句中。
如果文件具有扩展名,您可以使用以下代码,正如其他人所指出的,TPicture.LoadFromFile 会查看继承类注册的扩展名来确定要加载哪个图像。
uses
Graphics, Jpeg, pngimage, GIFImg;
procedure TForm1.Button1Click(Sender: TObject);
var
Picture: TPicture;
Bitmap: TBitmap;
begin
Picture := TPicture.Create;
try
Picture.LoadFromFile('C:\imagedata.dat');
Bitmap := TBitmap.Create;
try
Bitmap.Width := Picture.Width;
Bitmap.Height := Picture.Height;
Bitmap.Canvas.Draw(0, 0, Picture.Graphic);
Bitmap.SaveToFile('C:\test.bmp');
finally
Bitmap.Free;
end;
finally
Picture.Free;
end;
end;
如果文件扩展名未知,一种方法是查看前几个字节以确定图像类型。
procedure DetectImage(const InputFileName: string; BM: TBitmap);
var
FS: TFileStream;
FirstBytes: AnsiString;
Graphic: TGraphic;
begin
Graphic := nil;
FS := TFileStream.Create(InputFileName, fmOpenRead);
try
SetLength(FirstBytes, 8);
FS.Read(FirstBytes[1], 8);
if Copy(FirstBytes, 1, 2) = 'BM' then
begin
Graphic := TBitmap.Create;
end else
if FirstBytes = #137'PNG'#13#10#26#10 then
begin
Graphic := TPngImage.Create;
end else
if Copy(FirstBytes, 1, 3) = 'GIF' then
begin
Graphic := TGIFImage.Create;
end else
if Copy(FirstBytes, 1, 2) = #$FF#$D8 then
begin
Graphic := TJPEGImage.Create;
end;
if Assigned(Graphic) then
begin
try
FS.Seek(0, soFromBeginning);
Graphic.LoadFromStream(FS);
BM.Assign(Graphic);
except
end;
Graphic.Free;
end;
finally
FS.Free;
end;
end;
关于delphi - 加载 Jpg/Gif/Bitmap 并转换为 Bitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/959160/