第一行安卓代码——从相册中选择照片8.3.2
来源:互联网 发布:知己而知彼软件 编辑:程序博客网 时间:2024/06/04 20:07
8.3.1调用摄像头拍照
修改布局文件和MainActivity
见代码
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/activity_main" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/take_photo" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Take photo"/> <Button android:id="@+id/choose_from_album" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Choose From Album"/> <ImageView android:id="@+id/picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /></LinearLayout>
import android.Manifest;import android.annotation.TargetApi;import android.content.ContentUris;import android.content.Intent;import android.content.pm.PackageManager;import android.database.Cursor;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.net.Uri;import android.os.Build;import android.provider.DocumentsContract;import android.provider.MediaStore;import android.support.annotation.NonNull;import android.support.v4.app.ActivityCompat;import android.support.v4.content.ContextCompat;import android.support.v4.content.FileProvider;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.File;import java.io.FileNotFoundException;import java.io.IOError;import java.io.IOException;public class MainActivity extends AppCompatActivity { public static final int TAKE_PHOTO = 1; public static final int CHOOSE_PHOTO = 2; private ImageView picture; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button takePhoto = (Button) findViewById(R.id.take_photo); Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album); picture = (ImageView) findViewById(R.id.picture); takePhoto.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try { if(outputImage.exists() ) { outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if(Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO); } }); chooseFromAlbum.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } else { openAlbum(); } } }); } private void openAlbum() { Intent intent = new Intent("android.intent.action.GET_CONTENT"); intent.setType("image/*"); startActivityForResult(intent, CHOOSE_PHOTO); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PHOTO: if( resultCode == RESULT_OK ){ try{ Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); picture.setImageBitmap(bitmap); } catch (FileNotFoundException e){ e.printStackTrace(); } } break; case CHOOSE_PHOTO: if(resultCode == RESULT_OK){ //判断版本型号 if(Build.VERSION.SDK_INT >= 19) { //4.4以上版本 handleImageOnKitKat(data); } else { handleImageBeforeKitKat(data); } } break; default: break; } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 1: if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { openAlbum(); } else { Toast.makeText(this, "You denide the permission", Toast.LENGTH_SHORT).show(); } break; default: break; } } @TargetApi(19) private void handleImageOnKitKat(Intent data) { String imagePath = null; Uri uri = data.getData(); if(DocumentsContract.isDocumentUri(this, uri)) { //如果是document类型的uri,则通过document id处理 String docId = DocumentsContract.getDocumentId(uri); if("com.android.providers.media.documents".equals(uri.getAuthority())) { Toast.makeText(this, "success01", Toast.LENGTH_SHORT).show(); String id = docId.split(":")[1]; String secletion = MediaStore.Images.Media._ID + "=" + id; imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, secletion); } else if("com.android.providers.downloads.documents".equals(uri.getAuthority())) { Toast.makeText(this, "success02", Toast.LENGTH_SHORT).show(); Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId)); imagePath = getImagePath(contentUri, null); } } else if("content".equalsIgnoreCase(uri.getScheme())) { Toast.makeText(this, "success03", Toast.LENGTH_SHORT).show(); //如果是content类型的Uri,则使用普通方式处理 imagePath = getImagePath(uri, null); } else if("file".equalsIgnoreCase(uri.getScheme())) { //如果是file类型的uri,则直接获取文件路径 Toast.makeText(this, "success04", Toast.LENGTH_SHORT).show(); imagePath = uri.getPath(); } displayImage(imagePath); } private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String seclection) { String path = null; //通过Uri和secletion来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, seclection, null, null); if(cursor != null) { if(cursor.moveToFirst()) { path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA)); } cursor.close(); } return path; } private void displayImage(String imagePath) { if(imagePath != null) { Bitmap bitmap = BitmapFactory.decodeFile(imagePath); picture.setImageBitmap(bitmap); } else { Toast.makeText(this, "failed to get image", Toast.LENGTH_SHORT).show(); } }}
1 0
- 第一行安卓代码——从相册中选择照片8.3.2
- 第一行代码笔记——8.3.3 从相册中选择照片
- 从相册中选择照片
- 从相册中选择照片
- 安卓开发:从系统相册选择照片
- 《第一行代码》ChoosePicTest例子从相册读取照片显示失败
- 从相册中选择照片并返回~
- Android 从相册中选择照片
- android: 从相册中选择照片
- 第一行安卓代码——在活动中创建Menu2.2
- 多媒体之——从相册选择照片
- 安卓日记——一个从相册或者相机获取照片的工具类
- 第一行代码笔记 获取拍照照片和相册选取照片
- 读《第一行代码——安卓》2.3.3
- 第一行安卓代码——使用通知8.2
- 第一行安卓代码
- Android 调用摄像头拍照 以及 从相册中选择照片
- android从相册中选择报无法加载照片
- LeetCode 4 Median of Two Sorted Arrays 解题报告
- 紫书 例题11-1 公共表达式消除 UVa12219 表达式树,递归
- Recycleview实现复杂页面 三种以上布局 瀑布流 多布局 scrollview嵌套recyclerView 显示不全 滑动冲突 之进阶终极篇
- uboot 内存布局及启动过程
- Linux常用的配置文件整理
- 第一行安卓代码——从相册中选择照片8.3.2
- 迷宫
- winedt 破解方法和软件下载
- PAT1021. 个位数统计 (15)
- LeetCode 409. Longest Palindrome
- 你不能不知道到的Hook!
- BurpSuite系列(六)----Repeater模块(中继器)
- ActiveMQ的设置消息时长,事务,确认机制 ,持久化(五)
- 谷哥的小弟学后台(02)——MySQL(2)