我必须从
XML文件加载一个图像.
XML文件中没有关于图像是JPG / GIF / BMP的信息.加载图像后,我需要将其转换为Bitmap.
有没有人知道如何将图像转换为Bitmap而不知道实际的文件格式?我正在使用Delphi 2007/2009
谢谢.
解决方法
Delphi 2009内置支持JPEG,BMP,GIF和PNG.
对于早期版本的Delphi,您可能需要找到PNG和GIF的第三方实现,但在Delphi 2009中,您只需将Jpeg,pngimage和GIFImg单元添加到您的uses子句中即可.
如果文件具有扩展名,则可以使用以下代码,如其他人所述,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,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,3) = 'GIF' then begin Graphic := TGIFImage.Create; end else if Copy(FirstBytes,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;