调用Android摄像头与打开相册

来源:互联网 发布:java字符串长度函数 编辑:程序博客网 时间:2024/04/29 13:01

以下为代码块:


package com.example.demo;



import java.io.File;


import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio.Media;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;


public class MainActivity extends Activity {


public static final int TAKE_PHOTO = 1;
public static final int CROP_PHOTO = 2;
public static final int CHOOSE_PH = 3;


Button b, chooseFromAlbum;
ImageView pictrue;
Uri imageUri;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
pictrue = (ImageView) findViewById(R.id.imageView1);
chooseFromAlbum.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("image/*");
startActivityForResult(intent,CHOOSE_PH);//打开相册。
}
});
b.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
File outputImage = new File(Environment
.getExternalStorageDirectory(), "output_image.jpg");// Environment.getExternalStorageDirectory()获取SD卡的根目录.
try {
if (outputImage.exists()) {
outputImage.delete();
}
outputImage.createNewFile();


} catch (Exception e) {
// TODO: handle exception
}
imageUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 个人理解拍完放在imageUri下。
startActivityForResult(intent, TAKE_PHOTO);// 启动相机程序。
}
});
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {// requestCode:拍完照传回1,裁剪完传回2。
switch (requestCode) {
case TAKE_PHOTO:
if (resultCode == RESULT_OK) {
try {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);// 剪完放在放在imageUri下。
startActivityForResult(intent, CROP_PHOTO);// 启动裁剪程序。
} catch (Exception e) {
Log.i("test", "e=" + e);
}
}
break;
case CROP_PHOTO:
if (resultCode == RESULT_OK) {
try {
Bitmap bitMap = BitmapFactory
.decodeStream(getContentResolver().openInputStream(
imageUri));// 解码。
Log.i("test", "bitMap=" + bitMap);
pictrue.setImageBitmap(bitMap);// 将裁减的图片显示出来。
} catch (Exception e) {
Log.i("test", "e1=" + e);
}
}
break;
case CHOOSE_PH:
if(resultCode == RESULT_OK ){
//判断当前系统版本。
if(Build.VERSION.SDK_INT>=19){
// 4.4以上的系统版本使用这个方法处理。
handleImageOnKitKat(data);
}else{
// 4.4以下的系统版本使用这个方法处理。
handleImageBeforeKitKat(data);
}
}
break;
default:
break;
}
}
@TargetApi(19)
private void handleImageOnKitKat(Intent data){
String imagePath = null;
Uri uri = data.getData();
Log.i("test","4.4以上uri="+uri);
if(DocumentsContract.isDocumentUri(this, uri)){
String docId = DocumentsContract.getDocumentId(uri);
if("com.android.providers.media.documents".equals(uri.getAuthority())){
String id = docId.split(":")[1];
String selection = MediaStore.Images.Media._ID+"="+id;
imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
}else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
imagePath = getImagePath(contentUri,null);

}
}else if("content".equalsIgnoreCase(uri.getScheme())){
imagePath = getImagePath(uri,null);
}
//imagePath此时的路径为真实的手机图片的路径。
displayImage(imagePath);
}


private void handleImageBeforeKitKat(Intent data){
Uri uri = data.getData();
String imagePath = getImagePath(uri,null);
//imagePath此时的路径为真实的手机图片的路径。
displayImage(imagePath);
}
private String getImagePath(Uri uri,String selection){
String path = null;
// getContentResolver:获得内容解析;query:查询。
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if(cursor!=null){
if(cursor.moveToFirst()){
// getColumnIndex:获得列索引。
path = cursor.getString(cursor.getColumnIndex(Media.DATA));
}
cursor.close();
}
return path;
}
private void displayImage(String imagePath){
if(imagePath!=null){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
pictrue.setImageBitmap(bitmap);
}else{
Toast.makeText(this, "错误!", Toast.LENGTH_LONG).show();
}
}


}

以下为AndroidManifest.xml文件内容:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.demo"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="19" />
    <uses-permission android:name="androd.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/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>

以下为简单的布局文件:

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.choosepictest.MainActivity" >


    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="打开相机" />


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="131dp" />


    <Button
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="26dp"
        android:text="打开相册" />


</RelativeLayout>

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 狗摔了一下瘸了怎么办 小狗腿突然瘸了怎么办 狗腿突然瘸了怎么办 狗腿受伤了肿了怎么办 狗狗缺钙腿变形怎么办 小狗腿摔骨折了怎么办 狗狗脚掌被压了怎么办 狗狗的脚骨折了怎么办 给猫灌药水呛到怎么办 吃佐匹克隆白天工作量降低怎么办? 手机网页不显示图片怎么办啊 页眉页脚同前节怎么办 小米8后盖缝隙大怎么办 狗子生了一个不动的小狗怎么办 狗狗肚子有脓包怎么办 小孩幼儿园数学不开窍怎么办 老百姓打仗了报警派出所不管怎么办 和人打架报案了怎么办 皇上死后的妃子怎么办 武警改制警卫系的学员怎么办 正团病故后住房怎么办 遇到保姆式领导该怎么办 限购房子卖不了怎么办 斑马线礼让行人行人不走怎么办 中国留学生签证在美国被取消怎么办 建行卡网银帐号密码输入错误怎么办 建行卡密码忘了怎么办? 银行卡k宝丢了怎么办 k宝密码锁住了怎么办 农业银行k宝锁了怎么办 银行卡办的网银卡丢了怎么办 事业单位考察档案丢了怎么办 当兵政审家访家里没人在家怎么办 士兵转业结婚材料不全怎么办 体育生训练腿疼怎么办 车底盘刮的严重怎么办 新车底盘被刮了怎么办 车侧面刮凹了怎么办 憋气久了想呕吐怎么办 19岁网贷欠了3万怎么办 大学生欠2w网贷怎么办