Find out the type of file ( GIF, JPG, PNG) - DELPHI

南楼画角 提交于 2019-12-23 03:33:15

问题


I'm carrying images per URL and showing TImage . I will work with JPG , GIF and PNG . But I do not know how to find out what kind of extension possess each file, and then differentiate. How do I get header , or any other method for me to know what type of file: GIF or PNG or JPG?

var
  MS : TMemoryStream;
  GIf: TGIFImage;
  jpegimg: TJPEGImage;


begin
  MS := TMemoryStream.Create;
  GIf := TGIFImage.Create;
  jpegimg   := TJPEGImage.Create; ///////

  try
      try
        IdHTTP1.get('http://forum.wmonline.com.br/uploads/av-8929.jpg',MS);
        Ms.Seek(0,soFromBeginning);
        //Gif.LoadFromStream(MS);
        //Logo.Picture.Assign(GIF);
        jpegimg.LoadFromStream(MS);
        Logo.Picture.Assign(jpegimg);
      except
        ShowMessage('ERRO');
        Exit;
      end;
  finally
    FreeAndNil(GIF);
    FreeAndNil(MS);
    jpegimg.Free;  ////
  end;

回答1:


There are mechanisms intended to allow the description of the content of a request (or response), but any external meta-data may be unreliable, being wholly dependent upon an accurate implementation and setting of the meta-data involved. In some cases that meta-data may be incorrect or entirely missing.

Fortunately in common with many file formats, the specifications for the image file types you mention all mandate a specific header to identify the file (or stream) as conforming (or aspiring to conform) to the relevant specification.

The first 3 bytes of a GIF file are:

`G` `I` `F`    (ASCII)

You may also wish to check the subsequent 3 bytes for a valid GIF version number, also encoded in ASCII:

`8` `9` `a`   or `8` `7` `a`

The first 8 bytes of a PNG file have the values:

137 80 78 71 13 10 26 10   (decimal)

The first 2 bytes of a JPEG file are:

FF D8   (hex)

So to detect the format of the data in a response stream you need only inspect at most the first 8 bytes of the stream for one of these expected header values.




回答2:


I found a way to do what I want because there are URLs that do not show extensions .

Simply extract the image type from the server response:

header := IdHTTP1.Response.ContentType;

image/jpeg = JPG

image/gif = GIF

image/png = PNG



来源:https://stackoverflow.com/questions/31909745/find-out-the-type-of-file-gif-jpg-png-delphi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!