Created
October 16, 2013 08:50
-
-
Save epplestun/7004701 to your computer and use it in GitHub Desktop.
Get frame from MJPEG (Motion Webcams)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import java.awt.image.BufferedImage; | |
import java.io.BufferedInputStream; | |
import java.io.ByteArrayInputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.File; | |
import java.io.IOException; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import javax.imageio.ImageIO; | |
public class TestMJPG { | |
private byte[] curFrame; | |
private boolean frameAvailable = false; | |
private HttpURLConnection conn; | |
private BufferedInputStream httpIn; | |
private ByteArrayOutputStream jpgOut; | |
public static void main(String[] args) { | |
TestMJPG mp = new TestMJPG(args[0], args[1]); | |
} | |
public TestMJPG(String uri, String outputFilePath) { | |
try { | |
URL url = new URL(uri); | |
conn = (HttpURLConnection) url.openConnection(); | |
httpIn = new BufferedInputStream(conn.getInputStream(), 8192); | |
int prev = 0; | |
int cur = 0; | |
try { | |
while (httpIn != null && (cur = httpIn.read()) >= 0 && !frameAvailable) { | |
if (prev == 0xFF && cur == 0xD8) { | |
jpgOut = new ByteArrayOutputStream(8192); | |
jpgOut.write((byte) prev); | |
} | |
if (jpgOut != null) { | |
jpgOut.write((byte) cur); | |
} | |
if (prev == 0xFF && cur == 0xD9) { | |
curFrame = jpgOut.toByteArray(); | |
frameAvailable = true; | |
jpgOut.close(); | |
} | |
prev = cur; | |
} | |
} catch (IOException e) { | |
System.err.println("I/O Error: " + e.getMessage()); | |
} | |
ByteArrayInputStream jpgIn = new ByteArrayInputStream(curFrame); | |
BufferedImage bufImg = ImageIO.read(jpgIn); | |
File outputFile = new File(outputFilePath); | |
ImageIO.write(bufImg, "jpg", outputFile); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment