webcam包的使用介绍
上一篇文章网络聊天室里最后一个视频功能有提到这个包,因为我也是过来人,知道从无到有的困难,所以这里放上代码,介绍一下这个包的使用
TwoServer类
public class TwoServer {
Graphics g;
public void setUp(int port){
JFrame jf=new JFrame("视频");
jf.setSize(800,800);
jf.setVisible(true);
g=jf.getGraphics();
try{
ServerSocket server=new ServerSocket(port);
System.out.println("创建服务器成功");
while(true){
Socket client=server.accept();
System.out.println("连接到地址"+client.getRemoteSocketAddress());
DataInputStream dins=new DataInputStream(client.getInputStream());
while(true){
int k=dins.readInt();
byte[] data=new byte[k];
dins.read(data, 0, k);
this.DrawCapture(data);
}
}
}catch(Exception ef){
ef.printStackTrace();
}
}
public void DrawCapture(byte[] buffer){
ByteArrayInputStream bais=new ByteArrayInputStream(buffer);
try{
BufferedImage show=ImageIO.read(bais);
g.drawImage(show, 100, 100, null);
}catch(Exception ef){
ef.printStackTrace();
}
}
public static void main(String[] args){
TwoServer ss=new TwoServer();
ss.setUp(3569);
}
}
TwoClient类
public class TwoClient extends JFrame{
Graphics g;
Socket client;
public void DrawCapture(byte[] buffer){
ByteArrayInputStream bais=new ByteArrayInputStream(buffer);
try{
BufferedImage show=ImageIO.read(bais);
g.drawImage(show, 100, 100, null);
}catch(Exception ef){
ef.printStackTrace();
}
}
public void contact(String ip,int port)
throws IOException{
this.setTitle("视频");
this.setSize(800,800);
this.setLocationRelativeTo(null);
this.setVisible(true);
g=this.getGraphics();
Webcam web=Webcam.getDefault();
web.setViewSize(WebcamResolution.VGA.getSize());
web.open();
client=new Socket(ip,port);
System.out.println("连接成功");
while(true){
BufferedImage img=web.getImage();
g.drawImage(img, 100, 100, null);
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try {
ImageIO.write(img, "jpg", baos);
OutputStream ous=client.getOutputStream();
DataOutputStream dous=new DataOutputStream(ous);
dous.writeInt(baos.size());
//System.out.println(baos.size());
baos.writeTo(ous);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
TwoClient cc=new TwoClient();
try {
cc.contact("localhost", 3569);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
包自己下载好,导入到工程中,建立library,然后就可以用了,跑上面两个代码就会发现有两个视频出现了,然后再研究一下代码即可。
over~
本文详细介绍webcam包的使用,通过TwoServer和TwoClient类的代码实例,演示了如何在Java中实现视频流的发送与接收。文章覆盖了服务器端的设置、客户端的连接流程及视频帧的捕获与绘制。
1万+

被折叠的 条评论
为什么被折叠?



