I am writing an image file in my Java servlet. As it is getting it's data from a webcam I want to write to the file in an infinite loop to keep the image up to date.
I'm embedding the image file in my webpage, and using a JavaScript function to read the image every second. I start the servlet with a button in my webpage, which sends off a GET.
My problem is, and this may be obvious, that the servlet runs it's infinite writing loop and the image is not updated on the page. I can see in my file explorer that the image is written to constantly, but it's not updated on my page. I know that the JS function is being called as I tested it by writing the current time to the page, which was updating.
How can I get the image to be updated without this infinite loop?
Webpage:
<html>
<head>
<title>Webcam CCTV</title>
</head>
<body>
<img id='feed' src="img/frame.jpg" width='600' />
<form method="GET"
action="startCCTV.do">
<br><br>
<center>
<input type="SUBMIT"? value='Start'/>
</center>
</form>
<script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script src="js/main.js"></script>
</body>
</html>
main.js:
window.setInterval(function updateFrame() {
$("#feed").attr('src', 'img/frame.jpg');
}, 1000);
Controller:
public class CCTVStart extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
String contextPath = getServletContext().getRealPath("/");
ImageCapturer ic = new ImageCapturer(contextPath);
ic.captureImage();
}
}
Model:
public class ImageCapturer {
private String mContextPath;
public ImageCapturer(String contextPath) {
mContextPath = contextPath;
}
public void captureImage() throws IOException {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
FileOutputStream os = new FileOutputStream(
new File(mContextPath + "myLog.txt"));
os.write("\nStarting capture...".getBytes());
os.close();
VideoCapture camera = new VideoCapture(0);
Mat frame = new Mat();
camera.read(frame);
if (!camera.isOpened()) {
return;
}
while (true) {
if (camera.read(frame)) {
imwrite(mContextPath + "img\\frame.jpg", frame);
}
}
}
}