以下为代码块:
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>