delphi - 加载 Jpg/Gif/Bitmap 并转换为 Bitmap

标签 delphi image-processing bitmap vcl file-format

我必须从 XML 文件加载图像。 XML 文件中没有关于图像是否为 JPG/GIF/BMP 的信息。加载图像后,我需要将其转换为位图。

有人知道如何在不知道实际文件格式的情况下将图像转换为位图吗?我正在使用 Delphi 2007/2009

谢谢。

最佳答案

Delphi 2009 内置了对 JPEG、BMP、GIF 和 PNG 的支持。

对于早期版本的 Delphi,您可能需要找到 PNG 和 GIF 的第三方实现,但在 Delphi 2009 中,您只需添加 Jpegpngimage 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/

相关文章:

delphi - 为什么 Format 拒绝以 XE4 开头的过程地址参数

delphi - SAPI 与 Dephi : Async speech doesn't work

delphi - 快捷方式在第一个创建的表单而不是具有焦点的表单上触发 TAction

delphi - 在 Delphi 中使用 Assembly 的好资源?

python - 如何用scikit-image获取二值图像的骨架

c++ - Opencv cv::findchessboardCorners

java - 从图库中选择的图像不会在 ImageView 中设置

python - OpenCV,Python : Eliminating eventual narrowing when stitching images

bitmap - 使用 DirectShow 将电影文件转换为位图文件

java - Android ArrayAdapter 缓慢滚动