delphifreepascallazarusararat-synapse

Get image from web and display using Synapse


I want to get an image from the web into stream (without saving) and displaying it on TImage. The following code produces an error:

response := TMemoryStream.Create;
try
   HttpGetBinary('http://www.example-url/example_image.jpg', response);
   Image.Picture.LoadFromStream(response);
finally
   response.Free;
end;

Project ------- raised exception class 'EReadError' with message: Stream read error

This is the function in Synapse library(in the picture.inc) that the error points to:

function TPicFileFormatsList.FindByStreamFormat(Stream: TStream): TGraphicClass;
var
  I: Integer;
begin
  for I := Count - 1 downto 0 do
  begin
    Result := GetFormats(I)^.GraphicClass;
    if Result.IsStreamFormatSupported(Stream) then   // <<<<<< this is the error line
      Exit;
  end;
  Result := nil;
end;

Solution

  • You have to include the JPEGLib unit somewhere in your project, so that the JPEG graphic class gets registered.

    uses
      JPEGLib, // to support JPEG
      PNGcomn, // to support PNG
      httpsend;
    
    response := TMemoryStream.Create;
    try
       if HttpGetBinary('http://www.example-url/example_image.jpg', response) then
       begin
         response.Seek( 0, soFromBeginning );
         Image.Picture.LoadFromStream( response );
       end;
    finally
       response.Free;
    end;