webcam包的使用介绍

本文详细介绍webcam包的使用,通过TwoServer和TwoClient类的代码实例,演示了如何在Java中实现视频流的发送与接收。文章覆盖了服务器端的设置、客户端的连接流程及视频帧的捕获与绘制。

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~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值