Android-implement custom camera countdown to take photos, android custom

Source: Internet
Author: User
Tags dateformat

Android-implement custom camera countdown to take photos, android custom

This blog introduces the Android custom camera and implements the countdown camera function.

First, you can use the SurfaceView control to display the preview area of the photo. The following is the layout file:

Two textviews are used to display the prompt information and the number of seconds for countdown.

<RelativeLayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: background = "#266194" android: orientation = "vertical" tools: context = ". testActivity "> <SurfaceView android: id =" @ + id/surfaceView "android: layout_width =" match_parent "android: layout_height =" match_parent "android: layout_centerInParent = "true"/> <LinearLayout android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_centerInParent = "true" android: orientation = "vertical"> <TextView android: layout_width = "match_parent" android: layout_height = "wrap_content" android: text = "Please adjust the location to this region" android: textColor = "# ff0000" android: textSize = "32sp"/> <TextView android: id = "@ + id/TV _time" android: layout_width = "match_parent" android: layout_height = "wrap_content" android: paddingTop = "10dp" android: gravity = "center_horizontal" android: textColor = "#266194" android: textSize = "32sp"/> </LinearLayout> </RelativeLayout>

The following describes the specific implementation of mainActivity and detailed notes:

Package com. dhsr. pujiejia. ui; import java. io. file; import java. io. fileOutputStream; import java. text. simpleDateFormat; import java. util. date; import android. annotation. suppressLint; import android. app. activity; import android. content. context; import android. content. intent; import android. content. res. configuration; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. graphics. pi XelFormat; import android. hardware. camera; import android. hardware. camera. cameraInfo; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import android. view. surfaceHolder; import android. view. surfaceView; import android. view. window; import android. view. windowManager; import android. widget. textView; import com. example. pujiejiaapp. r; @ SuppressLint ({"NewApi", "SdCardPath"}) publ Ic class CameraActivity extends Activity implements Runnable {// preview image range private SurfaceView surfaceView; private TextView TV _time; // countdown shot private int cameratime = 4; private CameraActivity Camera; private boolean preview = false; // file name private String filename; // The timestamp private String timeString with the file name; // The formatting time private SimpleDateFormat dateFormat; // Date object private date Date; // control thread boolean stopThread = False; private File file; String photo; private Handler mHandler = new Handler () {public void handleMessage (android. OS. message msg) {int what = msg. what; switch (what) {case 222: TV _time.setText ("" + cameratime); if ("0 ". equals (TV _time.getText (). toString () {TV _time.setText ("Shooting successful! "); TakePhoto ();} break ;};};@ Override protected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stub super. onCreate (savedInstanceState); setContentView (R. layout. activity_test); CameraActivity. this. setFinishOnTouchOutside (false); // initialize data findView (); surfaceView. getHolder (). addCallback (new SufaceListener ();/* set the Surface below not to maintain its own buffer, but to wait for the screen rendering engine to push the content to the user */surfaceView. GetHolder (). setType (SurfaceHolder. SURFACE_TYPE_PUSH_BUFFERS); surfaceView. getHolder (). setFixedSize (200,200); // sets the resolution} @ Override protected void onStart () {// TODO Auto-generated method stub super. onStart (); // enable the Thread new Thread (this ). start ();} private final class SufaceListener implements SurfaceHolder. callback {/*** surface change */@ Override public void surfaceChanged (SurfaceHolder holder, int Format, int width, int height) {}/ *** surface creation */@ Override public void surfaceCreated (SurfaceHolder holder) {try {for (int I = 0; I <Camera. getNumberOfCameras (); I ++) {CameraInfo info = new CameraInfo (); Camera. getCameraInfo (I, info); // call the system's front camera if (info. facing = CameraInfo. CAMERA_FACING_FRONT) {camera = Camera. open (I) ;}} Camera. parameters parameters = camera. getParameters ();/* per second Capture 5 frames from the camera, */parameters. setPreviewFrameRate (5);/* set the photo output format: jpg */parameters. setPictureFormat (PixelFormat. JPEG);/* photo quality */parameters. set ("jpeg-quality", 85); WindowManager wm = (WindowManager) getSystemService (Context. WINDOW_SERVICE); camera. setParameters (parameters); camera. setPreviewDisplay (surfaceView. getHolder (); // use SurfaceView to display the video camera. startPreview (); preview = true;} catch (Exce Ption e) {}}/*** surface destruction */@ Override public void surfaceDestroyed (SurfaceHolder holder) {if (camera! = Null) {if (preview) camera. stopPreview (); camera. release (); camera = null; }}/ *** take a photo */private void takePhoto () {// perform the photo effect camera. takePicture (null, null, new Camera. pictureCallback () {@ Override public void onPictureTaken (byte [] data, Camera camera) {try {Bitmap bitmap = BitmapFactory. decodeByteArray (data, 0, data. length); timeString = formatDate (); // save it to the custom folder named filename = in the data/data Directory "/Data/com. example. pujiejiaapp/images/"+ timeString + ". jpg "; File file = new File (filename); boolean createNewFile = file. createNewFile () System. out. println ("failed to create folder" + createNewFile); System. out. println (file); FileOutputStream outStream = new FileOutputStream (file); bitmap. compress (Bitmap. compressFormat. JPEG, 60, outStream); outStream. flush (); outStream. close (); // browse camera again. stopPrevie W (); camera. startPreview (); preview = true;} catch (Exception e) {e. printStackTrace () ;}finally {}}) ;}@ Override public void run () {while (! StopThread) {try {// countdown to Thread in seconds. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} cameratime --; mHandler. sendEmptyMessage (222); if (cameratime <= 0) {break ;}}// initialize the data private void findView () {surfaceView = (SurfaceView) this. findViewById (R. id. surfaceView); TV _time = (TextView) findViewById (R. id. TV _time) ;}// format the System's time public String formatDate () {date = new Date (System. currentTimeMillis (); // Date Format dateFormat = new SimpleDateFormat ("'img '_ yyyyMMddHHmmss"); return dateFormat. format (date) ;}@ Override protected void onDestroy () {// TODO Auto-generated method stub // The thread has been disabled super. onDestroy (); stopThread = true ;}}

Detailed explanation of core code:

1. When creating a SurfaceView, The surfaceCreated () method

For (int I = 0; I <Camera. getNumberOfCameras (); I ++ ){
CameraInfo info = new CameraInfo ();
Camera. getCameraInfo (I, info );
// Call the system's front camera
If (info. facing = CameraInfo. CAMERA_FACING_FRONT ){
Camera = Camera. open (I );
}
}

This part of the Code indicates that the front camera CameraInfo. CAMERA_FACING_BACK is enabled by default when the camera is turned on. The front camera is CameraInfo. CAMERA_FACING_FRONT.

2. In the takePhoto () method:

Bitmap bitmap = BitmapFactory. decodeByteArray (data, 0,
Data. length );
TimeString = formatDate ();
Filename = "/data/com. example. pujiejiaapp/images /"
+ TimeString + ". jpg ";
Photo = timeString + ". jpg ";
File file = new File (filename );
Boolean createNewFile = file. createNewFile ();
FileOutputStream outStream = new FileOutputStream (file );
Bitmap. compress (Bitmap. CompressFormat. JPEG, 60, outStream );

This part of the code saves the captured image to the specified directory in bitmap format.

3. subthread used for countdown shooting

Public void run (){
While (! StopThread ){
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
Cameratime --;
MHandler. sendEmptyMessage (222 );
If (cameratime <= 0 ){
Break;
}
}
}

I hope you can understand the detailed comments of the core code. You are welcome to provide comments and hope to help you. Thank you!

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.