⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 democlient.java

📁 a zipped example for using a USB camera directly from Java
💻 JAVA
字号:
/**
 * Demo Code for demonstrating the ImageProcesor Package.
 */

import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.event.*;
import javax.media.*;
import javax.media.format.*;

public class DemoClient extends JFrame implements ActionListener, WindowListener, MouseListener, Runnable {
	
	private Container windowPane;
	private String buttonText[] = {"connect", "initPlayer", "Take Pic", "getPixel", "saveJPG", "getVideo", "endVideo"};
	private JButton buttonArray[];
	private PicCanvas canvas;
	private Font f1;
	private JTextArea output, input;
	private ImageProcessor imp;
	private Player player;
	private Image pic;
	private int mousex = 0;
	private int mousey = 0;
	private MediaTracker tracker;
	private Thread animator;
	private int delay = 0;
	
	//variables for tcp socket
	private Socket clientSocket;
	private DataOutputStream outToServer;
	private DataInputStream is;

	public static void main(String args[]) {
		DemoClient driver = new DemoClient();
	}
	
	public DemoClient() {
		super();
		windowPane = getContentPane();
		windowPane.setLayout(new BorderLayout());
		f1 = new Font ("Dialogue", Font.BOLD, 20);
		
		tracker = new MediaTracker(this);
		initOutputScreen();
		
		addWindowListener(this);
		this.setSize(600, 400);
		this.setVisible(true);
		
		imp = new ImageProcessor();
		player = null;
	}
	
	private void openConnection(String serverName) {
	    try {
		clientSocket = new Socket( (InetAddress.getByName(serverName)), 6789 );
		//clientSocket = new Socket( this.getCodeBase().getHost(), 8000 );
		outToServer = new DataOutputStream(clientSocket.getOutputStream());
		System.out.println("TCP connection established");
		is = new DataInputStream(clientSocket.getInputStream());
	    }
	    catch (Exception e) {
		System.out.println(e);
		System.out.println("TCP/IP connection failed.  Please try again.");
		return;
	    }
	}

	
	private void initOutputScreen()
	{
	    // top panel
	    JPanel pTop = new JPanel();
	    input = new JTextArea(2,50);
	    pTop.add(input);
	    windowPane.add(pTop, BorderLayout.NORTH);

		// picture Panel;
		canvas = new PicCanvas();
		canvas.addMouseListener(this);
		//pCenter.add(canvas);
		windowPane.add(canvas, BorderLayout.CENTER);
		
		// button Panel
		JPanel pRight = new JPanel();
		pRight.setLayout(new GridLayout(buttonText.length, 1));
		pRight.setBackground(Color.green);
		
		buttonArray = new JButton [buttonText.length];
		for (int i=0; i<(buttonText.length); i++)
		{
			buttonArray[i] = new JButton (buttonText[i]);
			buttonArray[i].setForeground(Color.blue);
			buttonArray[i].setFont(f1);
			buttonArray[i].addActionListener(this);
			pRight.add(buttonArray[i]);
		}
		windowPane.add(pRight, BorderLayout.EAST);
		
		// Bottom Text Window
		output = new JTextArea(5, 50);
		JPanel pBottom = new JPanel();
		pBottom.setBackground(Color.green);
		pBottom.add(output);
		windowPane.add(pBottom, BorderLayout.SOUTH);
	}

	
	public void actionPerformed(ActionEvent e) {
	try {
		// connect to Server
		if (e.getSource() == buttonArray[0]) {
			output.setText("");
			openConnection(input.getText());
			output.setText("connection established");
		}
		// init the camera
		else if (e.getSource() == buttonArray[1]) {
			output.setText("");
			// clear the inputStream and start over.
			is.skipBytes(is.available());
			outToServer.write(201);
			if (is.readInt() == 1)
			    output.setText("Player initialized");
			else
			    output.setText("Error on Server");
		}
		// get a picture
		else if (e.getSource() == buttonArray[2]) {
			output.setText("");
			is.skipBytes(is.available());
			outToServer.write(200);
			pic = recvImage(70, 15);
		}
		// get the rgb values of a specific pixel
		else if (e.getSource() == buttonArray[3]) {
			output.setText("");
			if (pic == null)
				output.setText("Please obtain a picture first");
			else {
				try {
					int[] newI = imp.getPixel(pic, mousex-70, mousey-15, 1, 1);
					int pixel = newI[0];
					int alpha = (pixel >> 24) & 0xff;
					int red   = (pixel >> 16) & 0xff;
					int green = (pixel >>  8) & 0xff;
					int blue  = (pixel      ) & 0xff;
					output.setText("Alpha: " + alpha + "\tRed: " + red + "\tGreen: " + green + "\tBlue: " + blue);
				}
				catch (InterruptedException exp) {}
			}
		}
		// save JPG
		else if (e.getSource() == buttonArray[4]) {
			output.setText("");
			is.skipBytes(is.available());
			outToServer.write(202);
			output.setText("JPG saved on server");
		}
		// get video
		else if (e.getSource() == buttonArray[5]) {
		    int fps = 5; //default value;
		    try {fps = Integer.parseInt(input.getText());} catch(Exception exp) {}

			try { outToServer.write(fps); }
			catch (Exception exp) {
				System.out.println("unable to send request to server");
			}
			delay = 1000 / fps; 
		
			animator = new Thread (this);
			animator.start();
		}
		// end video
		else if (e.getSource() == buttonArray[6]) {
			try { 
				outToServer.write(255);
				is.skipBytes(is.available());
			}
			catch (IOException exp) {}
			animator = null;
		}
	}
	catch(Exception exp) {exp.printStackTrace();}
	}
	
	private Image recvImage(int x, int y) throws Exception {
		int imageSize;
		int sizeRead = 0;
		
		// read the 1st 4 bytes of the image to determine its size.
		imageSize = is.readInt();
		//System.out.println("image size: " + imageSize);
	
		// read in the image file
		byte buffer[] = new byte[imageSize];
		while (sizeRead != imageSize) {
			sizeRead += is.read(buffer, sizeRead, (imageSize - sizeRead) );
		}
		
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		Image image = toolkit.createImage(buffer);
		
		//add the image to the media tracker
		tracker.addImage(image, 0);
		
		// wait for the image for finish loading and then paint on screen.
		try {
			tracker.waitForAll();
			canvas.setParams( image, x, y);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		tracker.removeImage(image);
		return image;
	}

	public void run() {
		long time = System.currentTimeMillis();
		while (Thread.currentThread() == animator) {
			// request new image from server
			
			try {
				recvImage(70, 15);
			}
			catch (Exception exp) {
				System.out.println("Failed to receive image from server");
				System.out.println("Please restart the applet");
				exp.printStackTrace();
			}
		
			// repaint canvas with new image.
			//pCenter.repaint();
			//pCenter.setParams( test, 0, 0);
			
			try {
				time += delay;
				Thread.sleep(Math.max(0, time - System.currentTimeMillis()));
			}
			catch (Exception e) {
				break;
			}
		}
	}


	
	public void windowClosing (WindowEvent e)
	{
		Window w = e.getWindow();
		w.dispose();
		animator = null;

		try {
  			animator = null;
  			is.skipBytes(is.available());
  			is.close();
	  		clientSocket.close();
	  		System.out.println("Connection Closed");
	  	}
	  	catch (IOException exp) {
	  		System.out.println("unable to close socket to server");
	  	}

	}
	
	public void windowClosed(WindowEvent e)
	{
		System.exit(0); 
	}
	 public void windowActivated(WindowEvent e){}
	 public void windowDeactivated(WindowEvent e){}
	 public void windowDeiconified(WindowEvent e){}
	 public void windowIconified(WindowEvent e) {}
	 public void windowOpened(WindowEvent e){}

	public void mouseClicked(MouseEvent e) {
	    if (pic != null) {
		mousex = e.getX();
		mousey = e.getY();
		output.setText("");
		output.setText("Coordinate: " + (mousex - 70) + " , " + (mousey - 15) );		
	    }
	}

	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {}
	public void mouseReleased(MouseEvent e) {}
	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -