Android Development handy notes using camera photo _android

Source: Internet
Author: User
Tags flush

In Android, there are two ways to use a camera to take photos, one is to call the system's own camera, the other is to write a camera interface.

We want to add the following permissions:

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission Android:name= "Android.permission.CAMERA"/>

1. Call System Camera

The main steps to invoke the camera of the system are:

(1) construct the path name of the picture store

(2) Activate camera activity using intent

(3) Write the captured picture to the file

(4) Display the picture in the Mainactivity

First, construct the picture name:

File FilePath = new file (Environment.getexternalstoragedirectory (), "Mycamera");
if (!filepath.exists ()) {
 filepath.mkdirs ();
}
FileName = new File (FilePath, System.currenttimemillis () + ". jpg");
try{
 if (!filename.exists ()) {
  filename.createnewfile ();
 }
} catch (Exception e) {
 e.printstacktrace ();
}

Then, start the camera activity:

Intent is used to start the system with its own camera
Intent Intent = new Intent (mediastore.action_image_capture);
Writes the result of the system camera to the file
 Intent.putextra (Mediastore.extra_output, Uri.fromfile (FileName));
Start intent the corresponding activity, return the default message
 Startactivityforresult (Intent, Activity.default_keys_dialer);

Finally, the picture is displayed in the mainactivity. At this point, we use the overloaded Onactivityresult () method to get the message returned by camera.

@Override
protected void onactivityresult (int requestcode, int resultcode, Intent data) {
 if (Requestcode = = Activity.default_keys_dialer) {
  //mainactivity receives the message returned by camera, and then displays the picture already written in ImageView
  Imageview.setimageuri (Uri.fromfile (FileName));
 }

The complete code is:

Import android.app.Activity;
Import android.content.Intent;
Import Android.net.Uri;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.provider.MediaStore;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.ImageView;
Import Java.io.File;
 public class Mainactivity extends activity {private File fileName = null;
 Private button button;
 Private ImageView ImageView;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Button = (button) Findviewbyid (R.id.button);
  ImageView = (ImageView) Findviewbyid (R.id.imageview); Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {File FilePath = n
    EW File (Environment.getexternalstoragedirectory (), "Mycamera");
    if (!filepath.exists ()) {filepath.mkdirs (); FileName = new File (FilePath, System.currenttimemillis () +.JPG ");
     try{if (!filename.exists ()) {filename.createnewfile ();
    }}catch (Exception e) {e.printstacktrace ();
    }//Intent is used to start the system with its own camera Intent Intent = new Intent (mediastore.action_image_capture);
    Writes the result of the system camera to the file Intent.putextra (Mediastore.extra_output, Uri.fromfile (fileName));
   Start intent the corresponding activity, return the default message Startactivityforresult (intent, Activity.default_keys_dialer);
 }
  }); @Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = activity. Default_keys_dialer) {//mainactivity receives the message returned by camera, and then displays the picture already written in ImageView Imageview.setimageuri (
  FileName)); }
 }
}

2. Write a camera interface for yourself

Write your own camera interface, the main application of the Surfaceview to display the camera screen. Then save the current screen with a button.

Again, we need to add camera and SDcard permissions:

<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission Android:name= "Android.permission.CAMERA"/>

First, we initialize the Surfaceview and add a corresponding callback to the Surfaceview:

Private Surfaceview Surfaceview;
Private Surfaceholder.callback Callback;
Surfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview);
 callback = new Surfaceholder.callback () {
  @Override public
  void surfacecreated (Surfaceholder holder) {
   Startcamera (); Used to start
  the camera}
  @Override public
  void surfacechanged (surfaceholder holder, int format, int width, int height) { c10/>}
  @Override public
  void surfacedestroyed (Surfaceholder holder) {
   stopcamera ();//To close the camera
  }
 };
 Surfaceview.getholder (). Addcallback (callback); Bind callback to Surfaceview

In the start of the camera, the first to open the camera connection, and then the image output to the Surfaceview, and then start the camera preview can be displayed on the Surfaceview camera screen, where the screen and the actual screen difference is 90 degrees, So we need to rotate the image 90 degrees before we can go in the same direction as the object we're shooting.

When you turn off the camera, just stop the preview and release the camera resources.

public void Startcamera () {
 camera = Camera.open ();
 try {
  Camera.setpreviewdisplay (Surfaceview.getholder ());
  Camera.setdisplayorientation (m);
  Camera.startpreview ();
 } catch (IOException e) {
  e.printstacktrace ();
 }
}
public void Stopcamera () {
 camera.stoppreview ();
 Camera.release ();
 camera = null;
}

Finally, to save the captured picture to SDcard, we click the button to take the picture and call the Camera.takepicture () method, which is the prototype:

/**
  * equivalent to takepicture (shutter, raw, NULL, JPEG).
  *
  * @see #takePicture (shuttercallback, Picturecallback, Picturecallback, Picturecallback)/public
 final void Takepicture (shuttercallback shutter, picturecallback raw,
   picturecallback jpeg) {
  takepicture ( Shutter, raw, NULL, JPEG);
 

     , Shutter is a callback that presses the shutter moment, which means that the Shuttercallback.onshutter () method is invoked instantaneously. Raw is a callback to an uncompressed image, that is, the Picturecallback.onpicturetaken () method is invoked when processing the original image data. JPEG is a callback when processing JPEG images, that is, we call this method when we need to save the image data in JPG format, Picturecallback.onpicturetaken (). Here we call this method to store the JPG image on the sdcard.

Button.setonclicklistener (New View.onclicklistener () {
  @Override public
  void OnClick (View v) {
   Camera.takepicture (NULL, NULL, new Camera.picturecallback () {
    @Override public
    void Onpicturetaken (byte[) Data, Camera Camera) {
     try {
      file FilePath = new File (Environment.getexternalstoragedirectory (), "Mycamera"); C8/>if (!filepath.exists ()) {
       filepath.mkdirs ();
      }
      File FileName = new file (FilePath, System.currenttimemillis () + ". jpg");
      Filename.createnewfile ();
      FileOutputStream fos = new FileOutputStream (fileName);
      Fos.write (data);
      Fos.flush ();
      Fos.close ();
     } catch (IOException e) {e.printstacktrace ();}}});
  }
 );

In this way, we have achieved using Surfaceview Preview camera screen, click button to save the current preview to SDcard.

The complete code is as follows:

Import android.app.Activity;
Import Android.hardware.Camera;
Import Android.os.Bundle;
Import android.os.Environment;
Import Android.view.SurfaceHolder;
Import Android.view.SurfaceView;
Import Android.view.View;
Import Android.widget.Button;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
 public class Mainactivity extends activity {private Camera Camera;
 Private button button;
 Private Surfaceview Surfaceview;
 Private Surfaceholder.callback Callback;
  @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_main);
  Button = (button) Findviewbyid (R.id.button);
  Surfaceview = (Surfaceview) Findviewbyid (R.id.surfaceview); callback = new Surfaceholder.callback () {@Override public void surfacecreated (Surfaceholder holder) {Startcamer
   A ();
@Override public void surfacechanged (surfaceholder holder, int format, int width, int height) {} @Override   public void surfacedestroyed (Surfaceholder holder) {Stopcamera ();
  }
  };
  Surfaceview.getholder (). Addcallback (callback); Button.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {Camera.takepictur
      E (null, NULL, new Camera.picturecallback () {@Override public void Onpicturetaken (byte[] data, Camera Camera) {
       try {file FilePath = new file (Environment.getexternalstoragedirectory (), "Mycamera");
       if (!filepath.exists ()) {filepath.mkdirs ();
       File FileName = new file (FilePath, System.currenttimemillis () + ". jpg");
       Filename.createnewfile ();
       FileOutputStream fos = new FileOutputStream (fileName);
       Fos.write (data);
       Fos.flush ();
      Fos.close ();
      catch (IOException e) {e.printstacktrace ();
   }
     }
    });
 }
  });
  public void Startcamera () {camera = Camera.open ();
 try {camera.setpreviewdisplay (Surfaceview.getholder ());  Camera.setdisplayorientation (90);
  Camera.startpreview ();
  catch (IOException e) {e.printstacktrace ();
  } public void Stopcamera () {Camera.stoppreview ();
  Camera.release ();
 camera = null; }
}

The above is described in this article about Android development Handy notes on the use of camera photos of all the content, I hope you like.

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.