The basic process is that android sends each frame of image data collected as a socket client, and the PC receives and displays each frame of image as a server for remote monitoring. The image is as follows (a photo taking function is added on the PC end later )...
(PS. Soon after I learned about Android and Java, I still don't understand many things. If the experts know where they can continue optimization, please give me more advice)
SystemCodeAs follows:
I. Android mobile client
(1) androidmanifest. xml file. Add the camera and socket permissions and setProgramActivity,
<? XML version = "1.0" encoding = "UTF-8"?> <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "org. wanghai. cameratest "Android: versioncode =" 1 "Android: versionname =" 1.0 "> <uses-SDK Android: minsdkversion =" 15 "/> <! -- Grant the App the permission to use the camera --> <uses-Permission Android: Name = "android. permission. camera "/> <uses-feature Android: Name =" android. hardware. camera "/> <uses-feature Android: Name =" android. hardware. camera. autofocus "/> <uses-Permission Android: Name =" android. permission. internet "/> <uses-Permission Android: Name =" android. permission. kill_background_processes "/> <uses-Permission Android: Name =" android. permission. restart_packages "/> <application Android: icon =" @ drawable/ic_launcher "Android: Label =" @ string/app_name "> <activity Android: Name = ". getip "Android: screenorientation =" Landscape "Android: Label =" @ string/app_name "> <intent-filter> <action Android: Name =" android. intent. action. main "/> <category Android: Name =" android. intent. category. launcher "/> </intent-filter> </activity> <activity Android: Name = ". cameratest "Android: screenorientation =" Landscape "Android: Label =" @ string/app_name "> </activity> </Application> </manifest>
(2) Set surfaceview in Main. XML to preview the captured image by the camera.
<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: Orientation = "vertical"> <surfaceview Android: id = "@ + ID/sview" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent" Android: scaletype = "fitcenter"/> </linearlayout>
(3) login. xml logon interface, used to enter the Server IP Address
<? XML version = "1.0" encoding = "UTF-8"?> <Tablelayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Id = "@ + ID/loginform" Android: Orientation = "vertical" Android: layout_width = "fill_parent" Android: layout_height = "fill_parent"> <tablerow> <textview Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: text = "IP:" Android: textsize = "10pt"/> <! -- Enter the text box of the user name --> <edittext Android: Id = "@ + ID/ipedittext" Android: layout_width = "fill_parent" Android: layout_height = "wrap_content" Android: digits = "0123456789. "Android: hint =" Enter the Server IP Address "Android: selectallonfocus =" true "/> </tablerow> </tablelayout>
(4) After obtaining the Server IP address from getip. Java, start the cameratest activity through intent and transmit the IP address information through bundle.
Public class getip extends activity {string ipname = NULL; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // sets the full screen requestwindowfeature (window. feature_no_title); getwindow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); setcontentview (R. layout. main); Final Builder = new alertdialog. builder (Th Is); // defines an alertdialog. builder object builder. settitle ("Login Server dialog box"); // set the title of the dialog box // load/RES/layout/login. XML interface layout tablelayout loginform = (tablelayout) getlayoutinflater (). inflate (R. layout. login, null); Final edittext iptext = (edittext) loginform. findviewbyid (R. id. ipedittext); builder. setview (loginform); // set the view object displayed in the dialog box // set a "login" button builder for the dialog box. setpositivebutton ("login" // set the listener for the button, new onclicklistener () {@ Override public void onclick (dialoginterface diich, int which) {// here you can execute the logon process ipname = iptext. gettext (). tostring (). trim (); bundle DATA = new bundle (); data. putstring ("ipname", ipname); intent = new intent (getip. this, cameratest. class); intent. putextras (data); startactivity (intent) ;}}); // set a "cancel" button builder for the dialog box. setnegativebutton ("cancel", new onclicklistener () {@ override public void onclic K (dialoginterface dialog, int which) {// cancel logon and do not do anything. System. Exit (1) ;}}); // create and display the dialog box builder. Create (). Show ();}}
(5) cameratest. Java program subject. After previewcallback is set, the onpreviewframe function of previewcallback is called every time an image data collection is completed. Here we convert the YUV format data to JPG, and then enable the thread to send the data through socket.
Public class cameratest extends activity {surfaceview sview; surfaceholder; int screenwidth, screenheight; camera; // defines the camera used by the system Boolean ispreview = false; // Private string ipname; @ suppresswarnings ("deprecation") @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); // sets the full screen requestwindowfeature (window. feature_no_title); getwind Ow (). setflags (windowmanager. layoutparams. flag_fullscreen, windowmanager. layoutparams. flag_fullscreen); setcontentview (R. layout. main); // obtain the IP address intent = getintent (); bundle DATA = intent. getextras (); ipname = data. getstring ("ipname"); screenwidth = 640; screenheight = 480; sview = (surfaceview) findviewbyid (R. id. sview); // obtain surfaceview component surfaceholder = sview in the interface. getholder (); // get surfacevie W's surfaceholder // Add a callback listener surfaceholder for surfaceholder. addcallback (New callback () {@ override public void surfacechanged (surfaceholder holder, int format, int width, int height) {}@ override public void surfacecreated (surfaceholder holder) {initcamera (); // open the camera} @ override public void surfacedestroyed (surfaceholder holder) {// If camera is not null, release the camera if (camera! = NULL) {If (ispreview) camera. stoppreview (); camera. release (); camera = NULL;} system. exit (0) ;}}); // you can specify this surfaceview as a buffer. settype (surfaceholder. surface_type_push_buffers);} private void initcamera () {If (! Ispreview) {Camera = camera. open ();} If (camera! = NULL &&! Ispreview) {try {Camera. parameters = camera. getparameters (); parameters. setpreviewsize (screenwidth, screenheight); // sets the size of the previewed photo parameters. setpreviewfpsrange (20, 30); // display 20 ~ 30 frames parameters. setpictureformat (imageformat. nv21); // set the image format parameters. setpicturesize (screenwidth, screenheight); // set the Photo size // camera. setparameters (parameters); // This line of code is not required after android2.3.3. setpreviewdisplay (surfaceholder); // use surfaceview to display the video camera. setpreviewcallback (New streamit (ipname); // sets the callback class camera. startpreview (); // start previewing camera. autofocus (null); // autofocus} catch (exception e) {e. PR Intstacktrace () ;}ispreview = true ;}} class streamit implements camera. previewcallback {private string ipname; Public streamit (string ipname) {This. ipname = ipname ;}@ override public void onpreviewframe (byte [] data, camera) {size = camera. getparameters (). getpreviewsize (); try {// call image. compresstojpeg () converts YUV format image data to JPG format yuvimage image = new yuvimage (data, imageformat. nv21, S Ize. Width, size. Height, null); If (image! = NULL) {bytearrayoutputstream outstream = new bytearrayoutputstream (); image. compresstojpeg (New rect (0, 0, size. width, size. height), 80, outstream); outstream. flush (); // enable the thread to send image data out thread th = new mythread (outstream, ipname); th. start () ;}} catch (exception ex) {log. E ("sys", "error:" + ex. getmessage () ;}} class mythread extends thread {private byte bytebuffer [] = new byte [1024]; private outputstre Am outsocket; private bytearrayoutputstream myoutputstream; private string ipname; Public mythread (bytearrayoutputstream myoutputstream, string ipname) {This. myoutputstream = myoutputstream; this. ipname = ipname; try {myoutputstream. close ();} catch (ioexception e) {e. printstacktrace () ;}} public void run () {try {// send the image data through socket Socket socket tempsocket = new socket (ipname, 6000); outsocket = temp Socket. getoutputstream (); bytearrayinputstream inputstream = new bytearrayinputstream (myoutputstream. tobytearray (); int amount; while (amount = inputstream. Read (bytebuffer ))! =-1) {outsocket. write (bytebuffer, 0, amount);} myoutputstream. flush (); myoutputstream. close (); tempsocket. close ();} catch (ioexception e) {e. printstacktrace ();}}}
2. PC server
imageserver. Java is used to display images and take photos
Public class imageserver {public static serversocket Ss = NULL; public static void main (string ARGs []) throws ioexception {Ss = new serversocket (6000 ); final imageframe frame = new imageframe (SS); frame. setdefaclocloseoperation (jframe. exit_on_close); frame. setvisible (true); While (true) {frame. panel. getimage (); frame. repaint () ;}}/ ** a frame with an image panel */@ suppresswarnings ("serial") Class Imageframe extends jframe {public imagepanel Panel; Public jbutton JB; Public imageframe (serversocket SS) {// get screen dimensions toolkit = toolkit. getdefatooltoolkit (); dimension screensize = kit. getscreensize (); int screenheight = screensize. height; int screenwidth = screensize. width; // center frame in screen settitle ("imagetest"); setlocation (screenwidth-default_width)/2, (screenheig Ht-default_height)/2); setsize (default_width, default_height); // Add panel to frame this. getcontentpane (). setlayout (null); Panel = new imagepanel (SS); panel. setsize (640,480); panel. setlocation (0, 0); add (panel); JB = new jbutton ("photo"); JB. setbounds (0,480,640, 50); add (jb); saveimage saveaction = new saveimage (SS); JB. addactionlistener (saveaction);} public static final int default_width = 640; Public static final int default_height = 560;}/** a panel that displays a tiled image */@ suppresswarnings ("serial") Class imagepanel extends jpanel {private serversocket SS; private image; private inputstream INS; Public imagepanel (serversocket SS) {This. ss = SS;} public void getimage () throws ioexception {socket S = This. SS. accept (); system. out. println ("connection successful! "); This. INS = S. getinputstream (); this. image = ImageIO. read (INS); this. INS. close ();} public void paintcomponent (Graphics g) {super. paintcomponent (g); If (image = NULL) return; G. drawimage (image, 0, 0, null) ;}} class saveimage implements actionlistener {randomaccessfile infile = NULL; byte bytebuffer [] = new byte [1024]; inputstream INS; private serversocket SS; Public saveimage (serversocket SS ){ This. ss = SS;} public void actionreceivmed (actionevent event) {try {socket S = ss. accept (); ins = S. getinputstream (); // The file selector opens jfilechooser jfc = new jfilechooser (". "); jfc. showsavedialog (New javax. swing. jframe (); // obtain the current selected file reference file savedfile = jfc. getselectedfile (); // If (savedfile! = NULL) {// read the data of the file. You can read the data in a fast manner every time. Try {infile = new randomaccessfile (savedfile, "RW");} catch (filenotfoundexception E) {e. printstacktrace () ;}} int amount; while (amount = ins. read (bytebuffer ))! =-1) {infile. write (bytebuffer, 0, amount);} infile. close (); ins. close (); S. close (); javax. swing. joptionpane. showmessagedialog (New javax. swing. jframe (), "saved successfully", "prompt! ", Javax. Swing. joptionpane. plain_message);} catch (ioexception e) {e. printstacktrace ();}}}
The open source code is as follows (android I use the 4.03 SDK, please change it for other versions. For versions earlier than 2.3.3, please note which line is commented out in initcamera)
It can only run successfully on the mobile phone of the android 4.04 system.
The following figure shows the startup screen when the test is successful:
Source code link:
Http://files.cnblogs.com/feifei1010/%E5%9F%BA%E4%BA%8Eandroid%E6%89%8B%E6%9C%BA%E7%9A%84%E8%BF%9C%E7%A8%8B%E8%A7%86%E9%A2%91%E7%9B%91%E6%8E%A7%E7%B3%BB%E7%BB%9F.rar
You are welcome to join the Group for discussion.Guangzhou super group 218251417,Nanjing group 220818530,Hangzhou group 253603803,Xiamen group 253604146