Android custom camera for autofocus and manual focus _android

Source: Internet
Author: User
Tags manual stub

Android custom camera for autofocus and manual focus:
Do not call the system camera, because different machines to open the camera rendering the interface is not uniform and can not meet the requirements.
So in order to allow the program on different machines to present a unified interface, and can be based on the requirements of the layout, do this demo.

The program implementation code is as follows:

Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Java.lang.reflect.Method;
Import Android.graphics.PixelFormat;
Import Android.hardware.Camera;
Import Android.hardware.Camera.AutoFocusCallback;
Import Android.hardware.Camera.Parameters;
Import Android.hardware.Camera.PictureCallback;
Import Android.hardware.Camera.ShutterCallback;
Import Android.os.Build;
Import Android.os.Bundle;
Import Android.util.Log;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.view.View.OnClickListener;

Import Android.widget.Button;
Import com.hp.classes.config.Constants;
Import Com.hp.classes.tools.CommonUtils;

Import com.hp.classes.ui.BaseActivity; @SuppressWarnings ("deprecation") public class Photographactivity extends baseactivity implements Onclicklistener,
  Surfaceholder.callback {private Surfaceview surfaceview;
  Private Camera Camera; Private Camera.parametERS parameters;
  Private Button btn_goback, Btn_takephoto;
  
  Private Surfaceholder Surfaceholder;
    @Override protected void OnDestroy () {Super.ondestroy ();
      if (camera!= null) {Camera.stoppreview ();
      Camera.release ();
    camera = null;
    } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.classes_activity_takephoto);
  Initview ();
    } @Override protected void Onresume () {super.onresume ();
  Initcamera ();
    private void Initview () {btn_goback = (Button) Findviewbyid (r.id.btn_goback);
    Btn_goback.setonclicklistener (this);
    Btn_takephoto = (Button) Findviewbyid (R.id.btn_takephoto);

    Btn_takephoto.setonclicklistener (this);
    Surfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);
    Surfaceview.setfocusable (TRUE);
    Surfaceview.setonclicklistener (this);
    Surfaceview.setbackgroundcolor (Trim_memory_background); SurfaceholdeR = Surfaceview.getholder ();
    Surfaceholder.settype (surfaceholder.surface_type_push_buffers);
    Surfaceholder.setkeepscreenon (TRUE);
    Surfaceholder.setfixedsize (400, 300);
  Surfaceholder.addcallback (this); @Override public void surfacedestroyed (Surfaceholder holder) {//TODO auto-generated a stub camera.sto
    Ppreview ();
    Camera.release ();

  camera = null;
      @Override public void surfacecreated (Surfaceholder holder) {//TODO auto-generated method stub try {
    Camera.setpreviewdisplay (Surfaceholder);
    catch (IOException e) {e.printstacktrace ();
    @Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {//Auto focus Camera.autofocus (New Autofocuscallback () {@Override public void Onautofocus (Boolean success, Camera camera
        {if (success) {Camera.cancelautofocus ();//Only if added this sentence, will automatically focus Doautofocus ();
  }
      }
    });}//Camera parameter initialization setting private void Initcamera () {if (null = camera) {camera = Camera.open ();
    } parameters = Camera.getparameters ();
    Parameters.setpictureformat (Pixelformat.jpeg);
    Parameters.setflashmode (Parameters.flash_mode_torch); if (! Build.MODEL.equals ("Koridy H30")) {Parameters.setfocusmode (Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
    1 Continuous Focus}else{Parameters.setfocusmode (Camera.Parameters.FOCUS_MODE_AUTO);
    } camera.setparameters (parameters);
    Setdispaly (camera);
    Camera.startpreview (); Camera.cancelautofocus ()//2 if you want to achieve continuous autofocus, this sentence must be added}//control the correct display direction of the image private void setdispaly (camera camera) {if (Integer.parseint (Build.VERSION.SDK) >= 8)
    {setdisplayorientation (camera,-90);
    else {parameters.setrotation (-90);
    }///implementation of the correct display of the image private void Setdisplayorientation (Camera Camera, int i) {method downpolymorphic; try {downpolymorphic = Camera.getclass (). gEtmethod ("Setdisplayorientation", new class[] {int.class});
      if (downpolymorphic!= null) {Downpolymorphic.invoke (camera, new object[] {i});
    The catch (Exception e) {log.e ("came_e", "image Error"); @Override public void OnClick (View v) {switch (V.getid ()) {case R.id.surfaceview:doautofocus ()
      ;
    Break
      Case R.id.btn_takephoto:takepicture ();
    Break
      Case R.id.btn_goback:finish ();
    Break
    Default:break;
    }//Handle button auto Focus private void Doautofocus () {parameters = Camera.getparameters ();
    Parameters.setfocusmode (Camera.Parameters.FOCUS_MODE_AUTO);
    Camera.setparameters (parameters); 
        Camera.autofocus (New Autofocuscallback () {@Override public void Onautofocus (Boolean success, camera camera) {
          if (success) {Camera.cancelautofocus ();//only by adding this sentence, will focus automatically. if (! Build.MODEL.equals ("Koridy H30")) {Parameters = Camera.getparameters (); Parameters.setfocusmode (Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);//1 Continuous Focus camera.setparameters (Paramet
          ERS);
            }else{parameters = Camera.getparameters ();
            Parameters.setfocusmode (Camera.Parameters.FOCUS_MODE_AUTO);
          Camera.setparameters (parameters);
  }
        }
      }
    });
  } private void Takepicture () {camera.takepicture (Shuttercallback, Rawcallback, Jpegcallback);
      }//define Shuttercallback shuttercallback Shuttercallback = new Shuttercallback () {public void Onshutter () {
    TODO do something the shutter closes.

  }
  }; Picturecallback rawcallback = new Picturecallback () {public void Onpicturetaken (byte[] data, Camera Camera) {/
    /TODO do something with the image RAW data.

  }
  }; Stroe the "picture in" format jpeg picturecallback jpegcallback = new Picturecallback () {public void Onpicturetake N (byte[] daTA, Camera Camera) {//Save the image JPEG data to the SD card fileoutputstream outstream = null;
        try {//Modify picture path and name String TempFileName = string.valueof (System.currenttimemillis ()) + ". jpg";
        File folder = Constants.cache_folder;
        if (!folder.isdirectory ()) {folder.mkdirs ();
        String Path = constants.cache_folder + File.separator + tempfilename;
        OutStream = new FileOutputStream (path);
        Outstream.write (data);
        Outstream.flush ();
        Outstream.close ();
      Surfaceview.setbackgrounddrawable (New Bitmapdrawable (Bitmapfactory.decodebytearray (data, 0, data.length));
      catch (FileNotFoundException e) {log.e ("TAG", "File note Found", e);
      catch (IOException e) {log.e ("TAG", "IO Exception", e);
}
    }
  };

 }

The

Classes_activity_takephoto.xml code is as follows:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android= "http://schemas.android.com/apk/res/" Android "Android:layout_width=" Match_parent "android:layout_height=" Match_parent "> <surfaceview android: Id= "@+id/surfaceview" android:layout_width= "match_parent" android:layout_height= "Match_parent" Android:layout_
    Alignparentleft= "true" android:layout_toleftof= "@+id/rlright"/> <linearlayout android:id= "@+id/rlright" Android:layout_width= "40DP" android:layout_height= "Match_parent" android:layout_alignparentright= "true" an Droid:background= "#2b2b2b" android:gravity= "center_horizontal" android:orientation= "vertical" > <linear
      Layout android:layout_width= "wrap_content" android:layout_height= "0dip" android:layout_weight= "1"
        android:gravity= "center" > <button android:id= "@+id/btn_goback" style= "@style/petextbutton"
 android:text= "Back"/>   </LinearLayout> <linearlayout android:layout_width= "wrap_content" android:layout_height= "0dip "android:layout_weight=" 1 "android:gravity=" center "> <button android:id=" @+id/btn_takep Hoto "style=" @style/petextbutton "android:text=" photo/> </LinearLayout> </linearlayout&gt

;

 </RelativeLayout>

You need to add the appropriate permissions in the manifest file:

  <uses-permission android:name= "Android.permission.CAMERA"/>
  <uses-feature android:name= " Android.hardware.camera "/>
  <uses-feature android:name=" Android.hardware.camera.autofocus "/>"

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.