Android 调用摄像头拍照 以及 从相册中选择照片
2015-10-30 15:38
639 查看
参考:《第一行代码》第8章
https://github.com/zxing/zxing
###########################################
新建一个工程CameraAndAlbumDemo:
一路默认,点击OK即可
修改activity_main.xml代码:
布局xml生成两个按钮,一个开启摄像头拍照,一个从相册中选择照片返回;同时设置一个ImageView用于显示返回的图片
修改MainActivity.java的代码:
AndroidManifest.xml代码:
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>
相关文章推荐
- Android中十六进制颜色的基本使用
- Android编程判断SD卡是否存在及使用容量查询实现方法
- Android获取公历年/月/日/星期 + 农历月/日
- Android-服务中监听电源键和Home键的广播
- Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()
- Android涉及到的设计模式
- Android 照片墙完整版,完美结合LruCache和DiskLruCache
- Android--------- Bitmap.Config ARGB_8888
- 《第一行代码——Android》之项目的目录结构
- Android编程实现读取手机联系人、拨号、发送短信及长按菜单操作方法实例小结
- Android开发---测试教程
- Fragment of Android
- 【android】禁止Edittext弹出软键盘并且使光标正常显示,androidedittext
- Android编程单击图片实现切换效果的方法
- Android按键事件处理流程 -- 从事件被派发到View层次结构的根节点DecorView开始分析
- Android基础入门教程——8.3.12 Paint API之—— PathEffect(路径效果)
- Android中visibility属性INVISIBLE与GONE的区别
- Android 屏蔽返回键、菜单键和Home键
- Android读取excel文件内容
- Android实际开发中的bug总结与解决方法(二)