Delphi异常错误加载远程图像

时间:2019-06-30 12:30:22

标签: delphi

嗨,我有以下代码:

procedure TformInvoiceDetails.ReadWebImage(imgAddress: string);
var
  memStream: TMemoryStream;
begin
  memStream := TMemoryStream.Create;
  try
    IdHTTP1.Get (imgAddress,memStream);
    //sleep(5000);
  except
    imageContProduct.Visible := false;
    ShowMessage('Image not found at:'+imgAddress);
    memStream.Free;
    exit;
  end;
  try
    memStream.Position := 0;
    imageContProduct.Visible := true;
    imageContProduct.Bitmap.LoadFromStream(memStream);
  finally
    memStream.Free;
  end;
end;

大多数情况下都可以,但是我不断出现exeption错误,有时还会出现“找不到图像”(尽管图像确实存在)。

如果我睡了(5000),一切正常。

因此,我假定在尝试添加到TImage之前,尚未恢复图像。

有没有更好的使用方法?

1 个答案:

答案 0 :(得分:0)

您可以使用其他组件加载图片:

uses WinInet, JPEG;
...
function DownloadToStream(Url: string; Stream: TStream): Boolean;
var
  hNet: HINTERNET;
  hUrl: HINTERNET;
  Buffer: array[0..10240] of Char;
  BytesRead: DWORD;
begin
  Result := FALSE;
  hNet := InternetOpen('agent', INTERNET_OPEN_TYPE_PRECONFIG, nil, nil, 0);
  if (hNet <> nil) then
  begin
    hUrl := InternetOpenUrl(hNet, PChar(Url), nil, 0,
      INTERNET_FLAG_RELOAD, 0);
    if (hUrl <> nil) then
    begin
      while (InternetReadFile(hUrl, @Buffer, sizeof(Buffer), BytesRead)) do
      begin
        if (BytesRead = 0) then
        begin
          Result := TRUE;
          break;
        end;
        Stream.WriteBuffer(Buffer,BytesRead);
      end;
      InternetCloseHandle(hUrl);
    end;
    InternetCloseHandle(hNet);
  end;
end;

procedure TformInvoiceDetails.ReadWebImage(imgAddress: string);
var
  memStream: TMemoryStream;
  Jpg:= TJPEGImage;
begin
  memStream:= TMemoryStream.Create;
  try
    if DownloadToStream(imgAddress, memStream) then
    begin
      memStream.Seek(0, soFromBeginning);
      if (LowerCase(RightStr(imgAddress, 4))='.jpg') or (LowerCase(RightStr(imgAddress, 5))='.jpeg')
        try //do the same operation for *.png
          Jpg:= TJPEGImage.Create;
          Jpg.LoadFromStream(memStream);
          imageContProduct.Picture.Bitmap.Assign(Jpg);
          imageContProduct.Visible := true;
        finally
          Jpg.Free;
        end
      else
        try
          imageContProduct.Picture.Bitmap.LoadFromStream(memStream);
          imageContProduct.Visible := true;
        finally
        end;
    end;
  finally
    memStream.Free;
  end;
end;