当前位置:   article > 正文

Android学习之调用相机和相册_"imageuri= fileprovider.geturiforfile(tuxiang.this

"imageuri= fileprovider.geturiforfile(tuxiang.this,\"com.buildmaterialapplicat"

调用摄像头拍照

修改布局文件中代码:

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. android:orientation="vertical"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <Button
  6. android:id="@+id/take_photo"
  7. android:layout_width="match_parent"
  8. android:layout_height="wrap_content"
  9. android:text="Take Photo"/> //用来打开摄像头进行拍照
  10. <ImageView
  11. android:id="@+id/picture"
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:layout_gravity="center_horizontal"/> //将拍到的图片显示出来
  15. </LinearLayout>

编写调用摄像头的具体逻辑。修改活动文件:

  1. public class MainActivity extends AppCompatActivity {
  2. public static final int TAKE_PHOTO = 1;
  3. private ImageView picture;
  4. private Uri imageUri;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. Button takePhoto = (Button) findViewById(R.id.take_photo);
  10. picture = (ImageView) findViewById(R.id.picture);
  11. takePhoto.setOnClickListener(new View.OnClickListener(){
  12. @Override
  13. public void onClick(View v){
  14. File outputImage = new File(getExternalCacheDir(),"output_image.jpg"); //创建了一个File对象,用于存放摄像头拍下的图片,并将它保存在SD卡的应用缓存目录下,用getExternalCacheDir()得到目录
  15. try{
  16. if(outputImage.exists()){
  17. outputImage.delete();
  18. }
  19. outputImage.createNewFile();
  20. }catch (IOException e) {
  21. e.printStackTrace();
  22. }
  23. if(Build.VERSION.SDK_INT>=24){ //若设备系统版本低于Android7.0,就调用Uri的fromFile()将File对象转换成Uri对象(表示着图片的本地真实路径)
  24. imageUri = FileProvider.getUriForFile(MainActivity.this,"com/example.cameraalbumtest.fileprovider",outputImage);//否则就调用FileProvider的getUriForFile()
  25. }else{
  26. imageUri = Uri.fromFile(outputImage); 方法将File对象转换成一个封装过的Uri对象
  27. }
  28. Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");//将这个Intent的action指定为android.media.action.IMAGE_CAPTURE
  29. intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);//置顶图片的输出地址
  30. startActivityForResult(intent,RAKE_PHOTO);
  31. }
  32. });
  33. }
  34. @Override
  35. protected void onActivityResult(int requestCode,int resultCode, Intent data){ //用startActivityForResult()启动活动会有结果返回到此方法中
  36. switch (requestCode){
  37. case TAKE_PHOTO:
  38. if(resultCode == RESULT_OK){
  39. try{
  40. //将拍摄的照片显示出来
  41. Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream((imageUri));
  42. picture.setImageBitmap(bitmap);
  43. }catch (FileNotFoundException e){
  44. e.printStackTrace();
  45. }
  46. }
  47. break;
  48. default:
  49. break;
  50. }
  51. }
  52. }

在AndroidMainfest.xml中对内容提供器(FileProvider)进行注册:

  1. <provider
  2. android:authorities="com.example.cameraalbumtest.fileprovider" //必须和干菜FileProvider.getUriForFile()方法中第二个参数一致
  3. android:name="android.support.v4.content.FileProvider" //此属性值是固定的
  4. android:exported="false"
  5. android:grantUriPermissions="true">
  6. <meta-data //<meta-data>来指定Uri的共享路径,并引用了一个@xml/file_path资源(下面我们来创建)
  7. android:name="android.support.FILE_PROVIDER_PATHS"
  8. android:resource="@xml/file_paths"/>
  9. </provider>

创建上面说的@xml/file_path资源

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <paths xmlns:andriod="http://schemas.android.com/apk/res/android">
  3. <enternal-path name="my_images" path=""/> //用来指定Uri共享,name属性值可以随便填,path属性的指标是共享的具体路径,此处为空表示共
  4. </paths> //享整个SD卡

在Android4.4之前,需要声明权限:

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  2. package="com.example.cameraalbumtest">
  3. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

从相册中选择照片

在上面的基础上在布局文件中添加:

  1. <Button
  2. android:id="@+id/choose_from_album"
  3. android:layout_width="match_parent"
  4. android:layout_height="wrap_content"
  5. android:text=""Choose From Album/>

然后修改MainActivity文件中代码,加入从相册选择照片的逻辑:(红色为新增)

  1. public class MainActivity extends AppCompatActivity {
  2. public static final int TAKE_PHOTO = 1;
  3. private ImageView picture;
  4. private Uri imageUri;
  5. public static final int CHOOSE_PHOTO = 2;
  6. @Override
  7. protected void onCreate(Bundle savedInstanceState) {
  8. super.onCreate(savedInstanceState);
  9. setContentView(R.layout.activity_main);
  10. Button takePhoto = (Button) findViewById(R.id.take_photo);
  11. Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);
  12. picture = (ImageView) findViewById(R.id.picture);
  13. takePhoto.setOnClickListener(new View.OnClickListener() {
  14. @Override
  15. public void onClick(View v) {
  16. File outputImage = new File(getExternalCacheDir(), "output_image.jpg");
  17. try {
  18. if (outputImage.exists()) {
  19. outputImage.delete();
  20. }
  21. outputImage.createNewFile();
  22. } catch (IOException e) {
  23. e.printStackTrace();
  24. }
  25. if (Build.VERSION.SDK_INT >= 24) {
  26. imageUri = FileProvider.getUriForFile(MainActivity.this, "com/example.cameraalbumtest.fileprovider", outputImage);
  27. } else {
  28. imageUri = Uri.fromFile(outputImage);
  29. }
  30. Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
  31. intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
  32. startActivityForResult(intent, RAKE_PHOTO);
  33. }
  34. });
  35. chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
  36. @Override
  37. public void onClick(View v) {
  38. if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //申请权限
  39. ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
  40. } else {
  41. openAlbum();
  42. }
  43. }
  44. });
  45. }
  46. private void openAlbum() {
  47. Intent intent = new Intent("android.intent.action.GET_CONTENT");//将他的action指定为“”中的
  48. intent.setType("image/*");
  49. startActivityForResult(intent, CHOOSE_PHOTO); //打开相册。第二个参数值为CHOOSE_PHOTO,
  50. } //当从相册选择完图片回到onActivityResult方法时,就会进入CHOOSE_PHOTO的case来处理图片
  51. @Override
  52. public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  53. switch (requestCode) {
  54. case 1:
  55. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  56. openAlbum();
  57. } else {
  58. Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show();
  59. }
  60. break;
  61. default:
  62. }
  63. }
  64. @Override
  65. protected void onActivityResult(int requestCode,int resultCode, Intent data){
  66. switch (requestCode){
  67. case TAKE_PHOTO:
  68. if(resultCode == RESULT_OK){
  69. try{
  70. //将拍摄的照片显示出来
  71. Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
  72. picture.setImageBitmap(bitmap);
  73. }catch (FileNotFoundException e){
  74. e.printStackTrace();
  75. }
  76. }
  77. break;
  78. case CHOOSE_PHOTO:
  79. if(resultCode == RESULT_OK) {
  80. if (Build.VERSION.SDK_INT >= 19) { //进行版本判断
  81. handleImageOnKitKat(data);
  82. } else {
  83. handleImageBeforeKitKat(data);
  84. }
  85. }
  86. break;
  87. default:
  88. break;
  89. }
  90. }
  91. @Target(19)
  92. private void handleImageOnKitKat(Intent data) { //如何解析这个封装过的Uri
  93. String imagePath = null;
  94. Uri uri = data.getData();
  95. if( DocumentsContract.isDocumentUri(this,Uri)){
  96. String docId = DocumentsContract.getDocumentId(uri);
  97. if ("com.android.providers.media.documents".equals(uri.getAuthority())){
  98. String id = docId.split(":")[1];
  99. String selection = MediaStore.Images.Media._ID + "=" + id;
  100. imagePath = getImagePath(MediaStore.Inages.Media.EXTERNAL_CONTENT_URI,selection);
  101. }else if("com.android.providers.downloads.documents"。equals(uri.getAuthority())){
  102. Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
  103. imagePath = getImagePath(contentUri, null);}
  104. }else if ("content".equalsIgnoreCase(uri.getScheme())){
  105. imagePath = getImagePath(uri,null);
  106. }else if ("file".equalsIgnoreCase(uri.getScheme())){
  107. imagePath = uri.getPath();
  108. }
  109. displayImage(imagePath);
  110. }
  111. private void handleImageBeforeKitKat(Intent data) {
  112. Uri uri = data.getData();
  113. String imagePath = getImagePath(rui,null);
  114. displayImage(imagePath);
  115. }
  116. private String getImagePath(Uri uri,String selection){
  117. String path = null;
  118. Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
  119. if(cursor != null){
  120. if(cursor.moveToFirst()){
  121. path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
  122. }
  123. cursor.close();
  124. }
  125. return path;
  126. }
  127. private void displayImage(String imagePath){
  128. if(imagePath != null){
  129. Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
  130. picture.setImageBitmap(bitmap);
  131. }else{
  132. Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT).show();
  133. }
  134. }
  135. }

应该有错,不过可以根据报错修改







声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/175341
推荐阅读
相关标签
  

闽ICP备14008679号