我有来自ip-camera的视频流,我想通过服务器处理这个流,所以我可以在我需要的任意数量的设备(如iPad /浏览器)上显示它(相机只有100Mbit / s所以很多设备都没有显示任何东西)。我有一个jetty http-Server正在运行。我写了一个获取流并将其转换为MjpegFrame的类:
MjpegFrame = frame;
try {
MjpegInputStream m = new MjpegInputStream(url.openStream());
MjpegFrame f;
while ((f = m.readMjpegFrame()) != null) {
if(!running) break;
frame = f;
}
m.close();
} catch (IOException e) {
//some error outputs
}
获取当前帧
public MjpegFrame getCurrentFrame() {
return frame;
}
这很好用。现在我试图用我的Servlet显示它,但在这里我只得到一张照片而不是一个流:
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String auth = request.getAuthType();
//System.out.println("auth:"+auth);
if(vm != null) {
MjpegFrame frame = vm.getCurrentFrame();
if(frame != null) {
BufferedOutputStream output = null;
try{
output = new BufferedOutputStream(response.getOutputStream(), 1024);
response.reset();
response.setBufferSize(1024);
response.setContentType("image/webp");
response.setHeader("Cache-Control", "max-age=0") ;
response.setHeader("Accept-Encoding", "gzip, deflate, sdch");
while(frame != null){
response.setContentLength(frame.getContentLength());
output.write(frame.getJpegBytes(), 0, frame.getContentLength());
frame = vm.getCurrentFrame();
}
}catch(Exception e){
e.printStackTrace();
}finally {
}
} else {
System.out.println("No image available...");
}
} else {
System.out.println("Error: VideoMultiplier is not set");
}
}
有谁知道我的代码出了什么问题?
答案 0 :(得分:0)
我自己解决了:
问题是Conent-Type
response.setContentType("image/webp");
我使用wireshark来分析它,并意识到响应应该看起来不同。无论如何,这就是我的回答:
String contentType = "multipart/x-mixed-replace; boundary=--yourboundary";
response.setContentType(contentType);
而不是--yourboundary你使用相机的边界,或者,为了使它更灵活,建立自己的标题:
public StringBuffer createHeader(int contentLength) {
StringBuffer header = new StringBuffer(100);
header.append("--yourboundary\r\nContent-Type: image/jpeg\r\nContent-Length: ");
header.append(contentLength);
header.append("\r\n\r\n");
return header;
}
然后像这样写:
frame = vm.getCurrentFrame();//here I get my frame of the current image I wanna send
StringBuffer header = createHeader(frame.getJpegBytes().length);
byte[] headerBytes = header.toString().getBytes();
byte[] imageBytes = frame.getJpegBytes();
// create a newImage array that is the size of the two arrays
byte[] newImage = new byte[headerBytes.length + imageBytes.length];
// copy headerBytes into start of newImage (from pos 0, copy headerBytes.length bytes)
System.arraycopy(headerBytes, 0, newImage, 0, headerBytes.length);
// copy imageBytes into end of newImage (from pos headerBytes.length, copy imageBytes.length bytes)
System.arraycopy(imageBytes, 0, newImage, headerBytes.length, imageBytes.length);
output.write(newImage,0,newImage.length);
output.flush();
希望它对某人有所帮助。
欢呼声