-1

How can I tell if a stream contains a picture or not? I am working with Delphi xe8 FMX developing an iOS application. I have a listbox and am loading pictures into the items. I can do this:

          if not Assigned(S) then
            s:=TMemoryStream.Create;
          if not Assigned(clHTTP) then
            clHTTP := TIDHTTP.Create;
          with clHTTP do
          begin
            clHTTP.HandleRedirects := True;
            clHTTP.AllowCookies := True;
            clHTTP.RedirectMaximum := 110000;
            clHTTP.Get(someimageURL,s);
          end;
          s.Seek(0,soFromBeginning);
          try
            LItem.ItemData.Bitmap.LoadFromStream(s);
          except
            clHTTP.Get(DefaultImageURL,s);
            s.Seek(0,soFromBeginning);
            LItem.ItemData.Bitmap.LoadFromStream(s);
          end;
          s.Free;
          clHTTP.Free;

I would prefer not to use a try-except block because it appears this causes loading of the bitmaps to be inconsistent. For example, I have to scroll the listbox items out of view, then back into view to see the pictures.

ThisGuy
  • 1,405
  • 1
  • 24
  • 51

1 Answers1

0

A quick way would be to check for the file signature. For instance, here are some common image format signatures:

  • PNG: 89 50 4E 47 0D 0A 1A 0A
  • JPEG: FF D8 FF E0
  • GIF87a: 47 49 46 38 37 61
  • GIF89a: 47 49 46 38 39 61

A comprehensive list can be found here: http://en.wikipedia.org/wiki/List_of_file_signatures

This approach will not prove that the rest of the stream is valid, but it is a good start and will allow you at least to reject obvious ringers.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • well, the thing is that some of the links I am using may or may not be broken. So.... 'pictureA.jpg' exists in the database as a valid URL but that is actually not true so when I attempt to load that picture via the url i get an error thrown. – ThisGuy May 06 '15 at 21:50
  • OK. Your question asks about the contents of a stream. Perhaps you could ask that other question as a different question, or see if it has already been asked. – David Heffernan May 06 '15 at 22:01
  • 1
    If you are requesting an image from a URL, the web server you are requesting from will tell you whether the image exists or not, and will tell you the actual image format (unless it just reports it as `application/octet-stream`, in which case you would have to resort to signature checking). – Remy Lebeau May 06 '15 at 22:20