相机捕捉图像。
我希望通过HTTP可以访问这张图片。
我能否使用TIdHTTPServer.OnCommandGet
事件来显示它?
我只想在TImage
中实时显示该图片。
如果可以,具体怎么做呢?
type
TGetImageStream = class(TIdSync)
protected
FStream: TStream;
procedure DoSynchronize; override;
public
class procedure GetImage(Stream: TStream);
end;
procedure TGetImageStream.DoSynchronize;
begin
Form1.Image1.Bitmap.SaveToStream(FStream);
end;
class procedure TGetImageStream.GetImage(Stream: TStream);
begin
with Create do
try
FStream := Stream;
Synchronize;
finally
Free;
end;
end;
procedure TForm1.HTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
Strm: TMemoryStream;
begin
Strm := TMemoryStream.Create;
try
TGetImageStream.GetImage(Strm);
Strm.Position := 0;
except
Strm.Free;
raise;
end;
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentType := 'image/bmp';
AResponseInfo.ContentStream := Strm;
end;
但如果您需要实时直播相机图像,则会变得有些棘手。您可以以几种不同的方式进行操作。例如,使用客户端拉取:
procedure TForm1.HTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
Strm: TMemoryStream;
begin
if ARequestInfo.Document = '' then
begin
AResponseInfo.Redirect('/');
end
else if ARequestInfo.Document = '/' then
begin
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentType := 'text/html';
AResponseIno.ContentText := '<html>'+EOL+
'<head>'+EOL+
'<title>Camera Image</title>'+EOL+
'<meta http-equiv="Refresh" content=5>'+EOL+
'</head>'+EOL+
'<body>'+EOL+
'<img src="/image">'+EOL+
'</body>'+EOL+
'</html>'+EOL;
end
else if ARequestInfo.Document = '/image' then
begin
Strm := TMemoryStream.Create;
try
TGetImageStream.GetImage(Strm);
Strm.Position := 0;
except
Strm.Free;
raise;
end;
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentType := 'image/bmp';
AResponseInfo.ContentStream := Strm;
end else begin
AResponseInfo.ResponseNo := 404;
end;
end;
procedure TForm1.HTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
Strm: TMemoryStream;
begin
Strm := TMemoryStream.Create;
try
AResponseInfo.ResponseNo := 200;
AResponseInfo.ContentType := 'multipart/x-mixed-replace; boundary=imgboundary';
AResponseInfo.CloseConnection := False;
AResponseInfo.WriteHeader;
AContext.Connection.IOHandler.WriteLn('--imgboundary');
repeat
Strm.Clear;
TGetImageStream.GetImage(Strm);
AContext.Connection.IOHandler.WriteLn('Content-type: image/bmp');
AContext.Connection.IOHandler.WriteLn;
AContext.Connection.IOHandler.Write(Strm);
AContext.Connection.IOHandler.WriteLn;
AContext.Connection.IOHandler.WriteLn('--imgboundary');
Sleep(5000);
until False;
finally
Strm.Free;
end;
end;
TIdHTTPServer
,因此可以使用Indy的TIdHTTP
作为客户端:IdHTTP1.Get('http://localhost/image', Strm); Strm.Position := 0; Image1.Picture.Bitmap.LoadFromStream(Strm);
。或者还有很多其他支持HTTP的第三方组件/库可用 - ICS、Synapse、libcurl、WinInet/WinHTTP等。 - Remy Lebeau
TImage
控件的VCL表单应用程序吗?我只是猜测。但这只解决了你问题的10%。 - Jerry Dodge