Basic tutorial for Android-9.3 using Camera

Source: Internet
Author: User

Basic tutorial for Android-9.3 using Camera
Basic tutorial for Android-9.3 using Camera

Tags (separated by spaces): basic Android tutorial

This section introduces

This section introduces the use of Camera in Android. Simply put, there are only two types of photos,
1. Call the system's built-in camera to take a photo, and then obtain the image after the photo
2. Either write a photo page by yourself
In this section, we will write two simple examples to experience the above two cases ~

1. The Calling System comes with Carema

The System camera can be called in the following sentence. After taking the camera, an intent is returned to onActivityResult.
The extra part of intent contains an encoded Bitmap ~

Intent it = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); startActivityForResult (it, Activity. DEFAULT_KEYS_DIALER); // Override the onActivityResult method @ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {if (requestCode = Activity. RESULT_ OK) {Bundle bundle = data. getExtras (); Bitmap bitmap = (Bitmap) bundle. get (data); img_show.setImageBitmap (bitmap );}}

Run:

This Fuzzy AV image quality... After all, it is a encoded Bitmap. By the way, the captured image will not be saved locally,
We can write code to save the image to our SD card and then display it. The picture will be much clearer,
Well, let's write the code to try it out ~

// Define a File variable private File currentImageFile to save the image = null; // write these items in the event of clicking the button, which is created on the SD card: @ Override public void onClick (View v) {File dir = new File (Environment. getExternalStorageDirectory (), pictures); if (dir. exists () {dir. mkdirs ();} currentImageFile = new File (dir, System. currentTimeMillis () +. jpg); if (! CurrentImageFile. exists () {try {currentImageFile. createNewFile ();} catch (IOException e) {e. printStackTrace () ;}} Intent it = new Intent (MediaStore. ACTION_IMAGE_CAPTURE); it. putExtra (MediaStore. EXTRA_OUTPUT, Uri. fromFile (currentImageFile); startActivityForResult (it, Activity. DEFAULT_KEYS_DIALER);} // onActivityResult: @ Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {if (requestCode = Activity. DEFAULT_KEYS_DIALER) {img_show.setImageURI (Uri. fromFile (currentImageFile ));}}

Okay, it's very simple. Let's take a look at the running results:

It is much clearer than the one above ~ It's so easy to call the built-in Carema of the system ~

2. Write a photo page by yourself

Here we need to use a SurfaceView as our preview interface, which is very simple to use!

Run:

Code Implementation:

Layout code:Activity_main.xml: A simple surfaceView + Button


      
       
   
  

MainActivity. java:

Public class MainActivity extends AppCompatActivity {private SurfaceView sfv_preview; private Button btn_take; private Camera camera = null; private SurfaceHolder. callback cpHolderCallback = new SurfaceHolder. callback () {@ Override public void surfaceCreated (SurfaceHolder holder) {startPreview () ;}@ Override public void surfaceChanged (SurfaceHolder holder, int format, int width, int height ){}@ Override public void surfaceDestroyed (SurfaceHolder holder) {stopPreview () ;};@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); bindViews ();} private void bindViews () {sfv_preview = (SurfaceView) findViewById (R. id. sfv_preview); btn_take = (Button) findViewById (R. id. btn_take); sfv_preview.getHolder (). addC Allback (cpHolderCallback); btn_take.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) {String path =; if (path = saveFile (data ))! = Null) {Intent it = new Intent (MainActivity. this, PreviewActivity. class); it. putExtra (path, path); startActivity (it);} else {Toast. makeText (MainActivity. this, failed to save the photo, Toast. LENGTH_SHORT ). show () ;}}) ;}}) ;}// Method for saving temporary files private String saveFile (byte [] bytes) {try {File file = File. createTempFile (img,); FileOutputStream fos = new FileOutputStream (file); fos. write (bytes); fos. flush (); fos. close (); return file. getAbsolutePath ();} catch (IOException e) {e. printStackTrace ();} return;} // start to preview private void startPreview () {camera = Camera. open (); try {camera. setPreviewDisplay (sfv_preview.getHolder (); camera. setDisplayOrientation (90); // rotate the camera for 90 degrees camera. startPreview ();} catch (IOException e) {e. printStackTrace () ;}/// stop previewing private void stopPreview () {camera. stopPreview (); camera. release (); camera = null ;}}

Finally, there is another PreviewActivity. java, where the image is displayed on the interface ~

/** * Created by Jay on 2015/11/22 0022. */public class PreviewActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        ImageView img = new ImageView(this);        String path = getIntent().getStringExtra(path);        if(path != null){            img.setImageURI(Uri.fromFile(new File(path)));        }        setContentView(img);    }}

Well, they are all very simple. Don't forget to add the permissions:

    
      
   
  

In addition, if carema is not released, the next call to carema will not report an error,
Error message: java. lang. RuntimeException: fail to connect to camera service
Therefore, you need to perform release () on Carema. If you keep reporting errors, restart your mobile phone ~

 

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.