我遵循以下可用代码。http://mrbool.com/java-image-processing-capturing-images-with-java-and-html5/30659
要求是捕获图像并将其存储在本地驱动器中。代码如下。
的index.html
<div>
<video id="videoID" autoplay style="border: 1px solid black;"></video>
</div>
<div>
<canvas id="canvasID" style="border: 1px solid black;"></canvas>
</div>
<div>
<input type="button" value="Take photo" onclick="capture()"
style="width: 200px; height: 30px;" /> <input type="button"
value="Send" onclick="send()" style="width: 200px; height: 30px;" />
</div>
<script type="text/javascript">
var video = document.getElementById('videoID');
var canvas = document.getElementById('canvasID');
var context = canvas.getContext('2d');
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia || navigator.mozGetUserMedia
|| navigator.msGetUserMedia;
navigator.getUserMedia({
video : true
}, function(stream) {
video.src = window.URL.createObjectURL(stream);
}, function(e) {
console.log('An error happened:', e);
});
function capture() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
};
function send() {
var imageData = canvas.toDataURL();
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/ImageServlet", true);
xmlhttp.send(imageData);
};
</script>
ImageServlet
package com.artigo.control;
import java.io.File;
import java.io.FileOutputStream;
import java.io.Reader;
import java.util.Random;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sun.misc.BASE64Decoder;
@WebServlet("/ImageServlet")
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
StringBuffer buffer = new StringBuffer();
Reader reader = request.getReader();
int current;
while ((current = reader.read()) >= 0)
buffer.append((char) current);
String data = new String(buffer);
data = data.substring(data.indexOf(",") + 1);
System.out.println("PNG image data on Base64: " + data);
FileOutputStream output = new FileOutputStream(new File(
"C:\\Users\\michael\\Desktop\\CapturedImages\\" + new Random().nextInt(100000) + ".png"));
output.write(new BASE64Decoder().decodeBuffer(data));
output.flush();
output.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
问题在于我能够捕获图像,但我无法将其保存到本地。请让我知道我哪里出错了,我该怎么办呢。
由于