문제

XML 파일에서 이미지를로드해야합니다. XML 파일에 이미지가 jpg/gif/bmp인지에 대한 정보가 없습니다. 이미지를로드 한 후 비트 맵으로 변환해야합니다.

실제 파일 형식을 모르고 이미지를 비트 맵으로 변환하는 방법에 대한 단서가 있습니까? Delphi 2007/2009를 사용하고 있습니다

고맙습니다.

도움이 되었습니까?

해결책 2

더 간단한 방법을 찾았습니다! 파일 형식을 알거나 확인하지 않고도 JPG/GIF/BMP 등을로드하고 이에 따라이를 변환합니다. 그것은 나를 위해 완벽하게 일했습니다.

여기서 공유 :)

Uses
Classes, ExtCtrls, Graphics, axCtrls;

Procedure TForm1.Button1Click(Sender: TObject);
Var
     OleGraphic               : TOleGraphic;
     fs                       : TFileStream;
     Source                   : TImage;
     BMP                      : TBitmap;
Begin
     Try
          OleGraphic := TOleGraphic.Create; {The magic class!}

          fs := TFileStream.Create('c:\testjpg.dat', fmOpenRead Or fmSharedenyNone);
          OleGraphic.LoadFromStream(fs);

          Source := Timage.Create(Nil);
          Source.Picture.Assign(OleGraphic);

          BMP := TBitmap.Create; {Converting to Bitmap}
          bmp.Width := Source.Picture.Width;
          bmp.Height := source.Picture.Height;
          bmp.Canvas.Draw(0, 0, source.Picture.Graphic);

          image1.Picture.Bitmap := bmp; {Show the bitmap on form}
     Finally
          fs.Free;
          OleGraphic.Free;
          Source.Free;
          bmp.Free;
     End;
End;

다른 팁

Delphi 2009에는 JPEG, BMP, GIF 및 PNG에 대한 내장 지원이 제공됩니다.

이전 버전의 Delphi의 경우 PNG 및 GIF에 대한 타사 구현을 찾아야 할 수도 있지만 Delphi 2009에서는 간단히 추가합니다. Jpeg, pngimage 그리고 GIFImg 귀하의 사용 조항에 대한 단위.

파일에 확장자가있는 경우 다른 코드를 사용할 수 있습니다. 다른 코드는 다른 코드를 사용할 수 있습니다. 다른 코드는 tpicture.loadfile을 상속 된 클래스에서 등록한 확장자를 검토하여로드 할 이미지를 결정합니다.

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;

당신은 사용할 수 없습니다 TPicture.LoadFromFile 그래픽에 어떤 형식이 있는지 모르는 경우,이 방법은 파일 확장자를 사용하여 등록 된 그래픽 형식을로드 해야하는 것을 결정하므로. 일치하지 않는 이유가 있습니다 TPicture.LoadFromStream 방법.

데이터를 검사하고 런타임시 그래픽 형식을 결정할 수있는 외부 라이브러리가 최상의 솔루션입니다. 당신은 사용할 수 있습니다 EFG 페이지 연구의 출발점으로.

빠르고 더러운 솔루션은 성공할 때까지 처리해야 할 몇 가지 형식을 시도하는 것입니다.

function TryLoadPicture(const AFileName: string; APicture: TPicture): boolean;
const
  GraphicClasses: array[0..3] of TGraphicClass = (
    TBitmap, TJPEGImage, TGIFImage, TPngImage);
var
  FileStr, MemStr: TStream;
  ClassIndex: integer;
  Graphic: TGraphic;
begin
  Assert(APicture <> nil);
  FileStr := TFileStream.Create('D:\Temp\img.dat', fmOpenRead);
  try
    MemStr := TMemoryStream.Create;
    try
      MemStr.CopyFrom(FileStr, FileStr.Size);
      // try various
      for ClassIndex := Low(GraphicClasses) to High(GraphicClasses) do begin
        Graphic := GraphicClasses[ClassIndex].Create;
        try
          try
            MemStr.Seek(0, soFromBeginning);
            Graphic.LoadFromStream(MemStr);
            APicture.Assign(Graphic);
            Result := TRUE;
            exit;
          except
          end;
        finally
          Graphic.Free;
        end;
      end;
    finally
      MemStr.Free;
    end;
  finally
    FileStr.Free;
  end;
  Result := FALSE;
end;

편집하다:

그만큼 그래피스 렉스 라이브러리 예가 있습니다 전환하다 그것은 사용합니다

GraphicClass := FileFormatList.GraphicFromContent(...);

그래픽 형식을 결정합니다. 이것은 당신이 언급 한 VB6 방법과 매우 유사합니다. 아마도 당신은 당신의 목적을 위해이 라이브러리를 사용할 수 있습니다.

나는 이것이 해당 버전 중 하나에서 작동하는지 확인하기 위해 Delphi 2007 또는 2009가 없습니다. 그러나 XE2에는 또 다른 클래스가 있습니다. Vcl.Graphics ~라고 불리는 TWICImage 그것은 다음에 의해 지원되는 이미지를 처리합니다 Microsoft 이미징 구성 요소, 포함 BMP, GIF, ICO, JPEG, PNG, TIF 및 Windows 미디어 사진. 스트림에서 이미지 유형을 감지 할 수 있습니다. 당신이 있다고 가정합니다 TImage 전화 형식으로 이미지 1:

procedure LoadImageFromStream(Stream: TStream; Image: TImage);
var
  wic: TWICImage;
begin
  Stream.Position := 0;
  wic := TWICImage.Create;
  try
    wic.LoadFromStream(Stream);
    Image.Picture.Assign(wic);
  finally
    wic.Free;
  end;
end;

procedure RenderImage(const Filename: string);
var
  fs: TFileStream;
begin
  fs := TFileStream.Create(Filename, fmOpenRead);
  try
    LoadImageFromStream(fs, Image1);
  finally
    fs.Free;
  end;
end;

추가하지 않고 작동합니다 PNGImage, GIFImg, 또는 JPEG 너의 ~에게 uses 성명.

다른 답변은 변환하는 방법을 보여줍니다 TImage BMP에, 그래서 나는 그것을 여기에 포함시키지 않습니다. 나는 다양한 그래픽 유형을 TImage 이미지 유형 또는 파일 확장자를 미리 알지 못하고 ...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top