这篇文章将为大家详细讲解有关怎么在Android中实现拍从相册中选取图片,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。获取图片方式: (类似更换头像的效果)手机拍照 选择图片;2、相册选取图
这篇文章将为大家详细讲解有关怎么在Android中实现拍从相册中选取图片,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
获取图片方式: (类似更换头像的效果)
手机拍照 选择图片;
2、相册选取图片;
创建xml布局文件(activity_main.xml ): 头部两个Button按钮,一个控制从相册选择照片,一个控制启动相册拍照选择图片。底部为一个ImageVIew,用于展示刚刚选择的图片。
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="Http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="16dp" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <Button android:id="@+id/btn_photo" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:background="@android:color/holo_red_light" android:text="相册选取" android:textColor="#FFF" android:textSize="16sp" /> <Button android:id="@+id/btn_camera" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_weight="1" android:background="@android:color/holo_red_light" android:text="拍照" android:textColor="#FFF" android:textSize="16sp" /> </LinearLayout> <!--展示选择的图片--> <ImageView android:id="@+id/image_show" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center_horizontal" android:layout_margin="6dp" /> </LinearLayout>
Android 4.4系统之前, 访问SD卡的应用关联目录需要声明权限的,从4.4系统开始不再需要权限声明。相关权限变成动态申请。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
第一部分:拍照获取图片
我们将拍照的图片放在SD卡关联缓存目录下。调用getExternalCacheDir()方法得到关联缓存目录, 具体的路径是/sdcard/Android/data/<package name>/cache。 那么为什么要使用应用关联缓目录来存放图片呢?因为从Android 6.0系统开始, 读写SD卡被列为了危险权限, 如果将图片存放在SD卡的任何其他目录, 都要进行运行时权限处理, 使用应用关联
目录则可以跳过这一步。
** * 拍照 或 从相册获取图片 */public class MainActivity extends AppCompatActivity { private Button btn_camera; private ImageView imageView; public static final int TAKE_CAMERA = 101; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btn_camera = (Button) findViewById(R.id.btn_camera); imageView = (ImageView) findViewById(R.id.image_show); //通过摄像头拍照 btn_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建File对象,用于存储拍照后的图片 //存放在手机SD卡的应用关联缓存目录下 File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try { if (outputImage.exists()) { outputImage.delete(); } } catch (Exception e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //大于等于版本24(7.0)的场合 imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage); } else { //小于android 版本7.0(24)的场合 imageUri = Uri.fromFile(outputImage); } //启动相机程序 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_CAMERA); } }); @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { switch (requestCode) { case TAKE_CAMERA: if (resultCode == RESULT_OK) { try { // 将拍摄的照片显示出来 Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri)); imageView.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; default: break; } }}
从Android 7.0开始, 直接使用本地真实路径的Uri被认为是不安全的, 会抛出一个FileUriExposedException异常。 FileProvider则是一种特殊的内容提供器, 它使用了和内容提供器类似的机制来对数据进行保护, 可以选择性地将封装过的Uri共享给外部, 从而提高了应用的安全性。
首先要在AndroidManifest.xml中对内容提供器进行注册了:
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.feige.pickphoto"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <cateGory android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <provider android:name="android.support.v4.content.FileProvider" android:authorities="com.feige.pickphoto.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider> </application> </manifest>
创建file_paths 资源文件:在res目录上右击——> new ——> Directory创建xml文件夹,然后在xml文件夹里新建file_paths.xml文件:
<?xml version="1.0" encoding="utf-8"?><paths xmlns:android="http://schemas.android.com/apk/res/android"> <!--external-path 就是用来指定Uri 共享的, name 属性的值可以随便填, path 属性的 值表示共享的具体路径。 这里设置 . 就表示将整个SD卡进行共享 --> <external-path name="my_images" path="." /></paths>
第二部分:从相册获取图片
public class MainActivity extends AppCompatActivity { private Button choose_photo; private ImageView imageView; public static final int PICK_PHOTO = 102; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); choose_photo = (Button) findViewById(R.id.btn_photo); imageView = (ImageView) findViewById(R.id.image_show); //从相册选择图片 choose_photo.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}, 101); } else { //打开相册 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT" intent.setType("image private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection) { String path = null; // 通过Uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, 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); imageView.setImageBitmap(bitmap); } else { Toast.makeText(this, "获取相册图片失败", Toast.LENGTH_SHORT).show(); } } }
共用拍照取图的FileProvider内容提供器。
*********完整MainActivity代码:
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.Nullable;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; public class MainActivity extends AppCompatActivity { private Button choose_photo; private Button btn_camera; private ImageView imageView; public static final int TAKE_CAMERA = 101; public static final int PICK_PHOTO = 102; private Uri imageUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); choose_photo = (Button) findViewById(R.id.btn_photo); btn_camera = (Button) findViewById(R.id.btn_camera); imageView = (ImageView) findViewById(R.id.image_show); //通过摄像头拍照 btn_camera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 创建File对象,用于存储拍照后的图片 //存放在手机SD卡的应用关联缓存目录下 File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try { if (outputImage.exists()) { outputImage.delete(); } } catch (Exception e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //大于等于版本24(7.0)的场合 imageUri = FileProvider.getUriForFile(MainActivity.this, "com.feige.pickphoto.fileprovider", outputImage); } else { //小于android 版本7.0(24)的场合 imageUri = Uri.fromFile(outputImage); } //启动相机程序 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //MediaStore.ACTION_IMAGE_CAPTURE = android.media.action.IMAGE_CAPTURE intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_CAMERA); } }); //从相册选择图片 choose_photo.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}, 101); } else { //打开相册 Intent intent = new Intent(Intent.ACTION_GET_CONTENT); //Intent.ACTION_GET_CONTENT = "android.intent.action.GET_CONTENT" intent.setType("image private void handleImageBeforeKitKat(Intent data) { Uri uri = data.getData(); String imagePath = getImagePath(uri, null); displayImage(imagePath); } private String getImagePath(Uri uri, String selection) { String path = null; // 通过Uri和selection来获取真实的图片路径 Cursor cursor = getContentResolver().query(uri, null, selection, 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); imageView.setImageBitmap(bitmap); } else { Toast.makeText(this, "获取图片失败", Toast.LENGTH_SHORT).show(); } } }
关于怎么在android中实现拍从相册中选取图片就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
--结束END--
本文标题: 怎么在android中实现拍从相册中选取图片
本文链接: https://www.lsjlt.com/news/269599.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
2024-05-16
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0