使用内置的Camera应用程序捕获图像

来源:互联网 发布:linux 自建邮局 编辑:程序博客网 时间:2024/06/06 04:05
package com.example.day01;import android.content.ContentResolver;import android.content.Intent;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.media.Image;import android.net.Uri;import android.os.Environment;import android.provider.MediaStore;import android.support.annotation.IntegerRes;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.widget.ImageView;import java.io.File;import java.io.FileNotFoundException;import java.net.URI;/** * 音视频联系一:使用内置的Camera应用程序捕获图像 */public class MainActivity extends AppCompatActivity {    private final int CAMERA_RESULT = 0;    ImageView view = null;    Uri uri;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        String imagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "capture1.jpg";        File imageFile = new File(imagePath);        uri = Uri.fromFile(imageFile);        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);    //打开相机//        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);   //通过uri方式将图片存起来与getImgFromCamera()使用        startActivityForResult(intent, CAMERA_RESULT);    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {        super.onActivityResult(requestCode, resultCode, intent);        if (resultCode == RESULT_OK) {            Bundle extras = intent.getExtras();            if (extras != null) {                Bitmap bitmap = (Bitmap) extras.get("data");                view = (ImageView) findViewById(R.id.backImage);                view.setImageBitmap(bitmap);    //显示一个小图像            }//            getImgFromCamera(); //通过uri的方式去获取得到的图片        }    }    /**     * 通过uri的方式去获取得到的图片     */    private void getImgFromCamera() {        ContentResolver cr = this.getContentResolver();        Bitmap cameraBitmap = null;        try {            if (cameraBitmap != null)                cameraBitmap.recycle();// 如果不释放的话,不断取图片,将会内存不够            cameraBitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));            view = (ImageView) findViewById(R.id.backImage);            view.setImageBitmap(cameraBitmap);        } catch (FileNotFoundException e) {            Log.e("error", "从相机中获取图片失败=====");            e.printStackTrace();        }    }}
0 0
原创粉丝点击