Android 调用摄像头拍照 以及 从相册中选择照片

来源:互联网 发布:大数据分析师培训课程 编辑:程序博客网 时间:2024/05/16 23:43

参考:《第一行代码》第8章

             https://github.com/zxing/zxing

###########################################


新建一个工程CameraAndAlbumDemo:

一路默认,点击OK即可


修改activity_main.xml代码:

<LinearLayout 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:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin"    android:orientation="vertical"    tools:context=".MainActivity">    <Button        android:id="@+id/btnCamera"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="take a photo" />    <Button        android:id="@+id/btnSelect"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="select an image" />    <RelativeLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content" >        <ImageView            android:id="@+id/ivCaptured"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_alignParentLeft="true"            android:layout_alignParentRight="true" />    </RelativeLayout></LinearLayout>

布局xml生成两个按钮,一个开启摄像头拍照,一个从相册中选择照片返回;同时设置一个ImageView用于显示返回的图片


修改MainActivity.java的代码:

package com.zj.cameraandalbumdemo;import android.app.Activity;import android.content.Intent;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;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.view.Window;import android.widget.Button;import android.widget.ImageView;import java.io.File;import java.text.SimpleDateFormat;import java.util.Date;public class MainActivity extends Activity {    private static final String LOG_TAG = "MainActivity";    private static final int REQUEST_IMAGE_CAPTURE = 100;  //request Code for camera    private static final int REQUEST_IMAGE_SELECT = 200;   //request Code for album    public static final int MEDIA_TYPE_IMAGE = 1;  //choose camera image type    private Button btnCamera; //相机拍摄    private Button btnSelect; //相册选择照片    private ImageView ivCaptured; //显示拍摄或相册选择的结果    private Uri fileUri;  //用于存储相机拍摄的照片    private Bitmap bmp;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE); //不显示标题栏        setContentView(R.layout.activity_main);        ivCaptured = (ImageView) findViewById(R.id.ivCaptured);        btnCamera = (Button) findViewById(R.id.btnCamera);        btnCamera.setOnClickListener(new Button.OnClickListener() {            public void onClick(View v) {                initPrediction();                fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); //得到存储地址的Uri                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //此action表示进行拍照                i.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  //指定图片的输出地址                startActivityForResult(i, REQUEST_IMAGE_CAPTURE);            }        });        btnSelect = (Button) findViewById(R.id.btnSelect);        btnSelect.setOnClickListener(new Button.OnClickListener() {            public void onClick(View v) {                initPrediction();                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //从相册选取一张图片                startActivityForResult(i, REQUEST_IMAGE_SELECT);            }        });    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        if ((requestCode == REQUEST_IMAGE_CAPTURE || requestCode == REQUEST_IMAGE_SELECT) && resultCode == RESULT_OK) {            String imgPath;            if (requestCode == REQUEST_IMAGE_CAPTURE) {                imgPath = fileUri.getPath(); //取得拍照存储的地址            } else { //解析得到所选相册图片的地址                Uri selectedImage = data.getData();                String[] filePathColumn = { MediaStore.Images.Media.DATA };                Cursor cursor = MainActivity.this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);                cursor.moveToFirst();                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);                imgPath = cursor.getString(columnIndex);                cursor.close();            }            bmp = BitmapFactory.decodeFile(imgPath); //将所选图片提取为bitmap格式            Log.d(LOG_TAG, imgPath);            Log.d(LOG_TAG, String.valueOf(bmp.getHeight()));            Log.d(LOG_TAG, String.valueOf(bmp.getWidth()));            ivCaptured.setImageBitmap(bmp); //show image        }        btnCamera.setEnabled(true);        btnSelect.setEnabled(true);    }    private void initPrediction() {        btnCamera.setEnabled(false);        btnSelect.setEnabled(false);    }    /** Create a file Uri for saving an image or video */    /** 为保存图片或视频创建一个文件地址 */    private static Uri getOutputMediaFileUri(int type){        return Uri.fromFile(getOutputMediaFile(type));    }    /** Create a File for saving an image or video */    private static File getOutputMediaFile(int type){        // To be safe, you should check that the SDCard is mounted        // using Environment.getExternalStorageState() before doing this.        // 首先检测外部SDCard是否存在并且可读可写        if (!Environment.getExternalStorageState().equals("mounted")) {            return null;        }        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(                Environment.DIRECTORY_PICTURES), "Caffe-Android-Demo");        // This location works best if you want the created images to be shared        // between applications and persist after your app has been uninstalled.        // 如果存储路径不存在,则创建        // Create the storage directory if it does not exist        if (! mediaStorageDir.exists()) {            if (! mediaStorageDir.mkdirs()) {                Log.d("MyCameraApp", "failed to create directory");                return null;            }        }        // Create a media file name        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());        File mediaFile;        if (type == MEDIA_TYPE_IMAGE) {            mediaFile = new File(mediaStorageDir.getPath() + File.separator +                    "IMG_"+ timeStamp + ".jpg");        } else {            return null;        }        return mediaFile;    }}


AndroidManifest.xml代码:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.zj.cameraandalbumdemo" >    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <!-- CAMERA -->    <uses-permission android:name="android.permission.CAMERA" />    <uses-feature android:name="android.hardware.camera" />    <uses-feature android:name="android.hardware.camera.autofocus" />    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name=".MainActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>


0 0
原创粉丝点击