Android 图片选择器、图片剪切,文件选择器

单张图片选择

1、在build.gradle中dependencies下添加依赖

compile 'com.github.lovetuzitong:MultiImageSelector:1.2'

2、完整activity代码

public class MainActivity extends AppCompatActivity {private static final int REQUEST_IMAGE3 = 5;public final static int MSG_DO_CUTOUT_GET_PIC = 66;private String path;private File compressedImage1File;//切图private int nMultiple;private String PhotoPath;private File filePhoto;private int nPreX = 3;private int nPreY = 3;private String strTakePicName = "yxbl.jpg";private static final String[] authBaseArr = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};private static final int authBaseRequestCode = 1;private ImageView imageView;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initNavi();//权限方法initZoom();//初始化切图imageView = (ImageView)findViewById(R.id.testimage);imageView.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {MultiImageSelector.create(MainActivity.this).showCamera(true) // 是否显示相机. 默认为显示
//                .count(6) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效.single() // 单选模式
//                    .multi() // 多选模式, 默认模式;
//                    .origin(strings) // 默认已选择图片. 只有在选择模式为多选时有效.start(MainActivity.this, REQUEST_IMAGE3);}});}public void initZoom(){DisplayMetrics dm = new DisplayMetrics();getWindowManager().getDefaultDisplay().getMetrics(dm);nMultiple = dm.widthPixels;PhotoPath = getImageSavePath(this) + "";createFolder(PhotoPath);}public static void createFolder(String strPath) {File file = new File(strPath);if (!file.exists())file.mkdirs();}public static String getImageSavePath(Context context) {File dataDir ;String path ;if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {dataDir = Environment.getExternalStorageDirectory();path = context.getString(R.string.SDcardPath);} else {dataDir = Environment.getDataDirectory();path = context.getString(R.string.DataPath);}StringBuffer DataPath = new StringBuffer();StringBuffer cachePath = new StringBuffer();DataPath.append(dataDir.getPath()).append(path);cachePath.append(DataPath.toString()).append(".cache");File cache = new File(cachePath.toString());if (!cache.exists()) {cache.mkdirs();}return DataPath.toString();}@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {super.onActivityResult(requestCode, resultCode, data);List<LocalMedia> images;if (resultCode == RESULT_OK) {switch (requestCode) {case 5:if (requestCode == REQUEST_IMAGE3) {if (resultCode == RESULT_OK) {List<String> pathImage = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
//                            strings = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);for (int a = 0; a < pathImage.size(); a++) {path = pathImage.get(0);compressedImage1File = new File(path);// String param = compressedImage1File.getPath();
//                                Bitmap bitmap= BitmapFactory.decodeFile(param);
//                                imageView.setImageBitmap(bitmap);startPhotoZoom(Uri.fromFile(compressedImage1File));//切图方法}}}break;case MSG_DO_CUTOUT_GET_PIC:String param2=  filePhoto.getPath();Bitmap bitmap2= BitmapFactory.decodeFile(param2);imageView.setImageBitmap(bitmap2);break;}}}//开启截图public void startPhotoZoom(Uri uri) {strTakePicName = getTime() + "yxbl.jpg";filePhoto = new File(PhotoPath, strTakePicName);Intent intent = new Intent("com.android.camera.action.CROP");intent.setDataAndType(uri, "image/*");// crop为true是设置在开启的intent中设置显示的view可以剪裁intent.putExtra("crop", "true");// aspectX aspectY 是宽高的比例intent.putExtra("aspectX", nPreX);intent.putExtra("aspectY", nPreY);// outputX,outputY 是剪裁图片的宽高intent.putExtra("outputX", nMultiple);intent.putExtra("outputY", nPreY * nMultiple / nPreX);intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePhoto));intent.putExtra("return-data", false);intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());intent.putExtra("noFaceDetection", true); // no face detection
//        Log.v("lgq", "startPhotoZoom=//开启截图=====" + compressedImage1File);startActivityForResult(intent, MSG_DO_CUTOUT_GET_PIC);}public String getTime() {long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳String str = String.valueOf(time);return str;}private boolean hasBasePhoneAuth() {PackageManager pm = getPackageManager();for (String auth : authBaseArr) {if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {return false;}}return true;}private void initNavi() {StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();StrictMode.setVmPolicy(builder.build());builder.detectFileUriExposure();// 申请权限if (android.os.Build.VERSION.SDK_INT >= 23) {if (!hasBasePhoneAuth()) {this.requestPermissions(authBaseArr, authBaseRequestCode);return;}}}}

下篇多图选择器:https://mp.csdn.net/postedit/82115774

 

文件选择器

1、工具方法

/*** 作者:created by meixi* 邮箱:1085220040@qq.com* 日期:2019/12/13 13:50*/
public class ContentUriUtil {/*** Get a file path from a Uri. This will get the the path for Storage Access* Framework Documents, as well as the _data field for the MediaStore and* other file-based ContentProviders.** @param context The context.* @param uri The Uri to query.* @author paulburke*/public static String getPath(final Context context, final Uri uri) {final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;;// DocumentProviderif (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {// ExternalStorageProviderif (isExternalStorageDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];if ("primary".equalsIgnoreCase(type)) {return Environment.getExternalStorageDirectory() + "/" + split[1];}// TODO handle non-primary volumes}// DownloadsProviderelse if (isDownloadsDocument(uri)) {final String id = DocumentsContract.getDocumentId(uri);final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));return getDataColumn(context, contentUri, null, null);}// MediaProviderelse if (isMediaDocument(uri)) {final String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}final String selection = "_id=?";final String[] selectionArgs = new String[] {split[1]};return getDataColumn(context, contentUri, selection, selectionArgs);}}// MediaStore (and general)else if ("content".equalsIgnoreCase(uri.getScheme())) {// Return the remote addressif (isGooglePhotosUri(uri))return uri.getLastPathSegment();return getDataColumn(context, uri, null, null);}// Fileelse if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return null;}/***** Get the value of the data column for this Uri. This is useful for* MediaStore Uris, and other file-based ContentProviders.** @param context The context.* @param uri The Uri to query.* @param selection (Optional) Filter used in the query.* @param selectionArgs (Optional) Selection arguments used in the query.* @return The value of the _data column, which is typically a file path.*/public static String getDataColumn(Context context, Uri uri, String selection,String[] selectionArgs) {Cursor cursor = null;final String column = "_data";final String[] projection = {column};try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,null);if (cursor != null && cursor.moveToFirst()) {final int index = cursor.getColumnIndexOrThrow(column);return cursor.getString(index);}} finally {if (cursor != null)cursor.close();}return null;}/*** @param uri The Uri to check.* @return Whether the Uri authority is ExternalStorageProvider.*/public static boolean isExternalStorageDocument(Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is DownloadsProvider.*/public static boolean isDownloadsDocument(Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is MediaProvider.*/public static boolean isMediaDocument(Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}/*** @param uri The Uri to check.* @return Whether the Uri authority is Google Photos.*/public static boolean isGooglePhotosUri(Uri uri) {return "com.google.android.apps.photos.content".equals(uri.getAuthority());}}

 

2、实现activity

public class Main2Activity extends AppCompatActivity {private TextView filePath;private Button btnSelect;private static final String[] authBaseArr = {//申请类型Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,};private static final int authBaseRequestCode = 1;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main2);filePath = findViewById(R.id.open_file);btnSelect = findViewById(R.id.file_path);initNavi();btnSelect.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {openSystemFile();}});}public void openSystemFile() {Intent intent = new Intent(Intent.ACTION_GET_CONTENT);// 所有类型intent.setType("*/*");intent.addCategory(Intent.CATEGORY_DEFAULT);intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);try {startActivityForResult(Intent.createChooser(intent, "请选择文件"), 1);} catch (ActivityNotFoundException e) {e.printStackTrace();Toast.makeText(Main2Activity.this, "请安装文件管理器", Toast.LENGTH_SHORT).show();}}@Overrideprotected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {super.onActivityResult(requestCode, resultCode, data);if (requestCode == 1 && resultCode == Activity.RESULT_OK) {//Get the Uri of the selected fileUri uri = data.getData();if (null != uri) {String path = ContentUriUtil.getPath(this, uri);Log.i("filepath", " = " + path);updateFilePath(path);}}}private void updateFilePath(final String path) {runOnUiThread(new Runnable() {@Overridepublic void run() {filePath.setText(path);}});}private boolean hasBasePhoneAuth() {PackageManager pm = getPackageManager();for (String auth : authBaseArr) {if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {return false;}}return true;}private void initNavi() {// 申请权限if (android.os.Build.VERSION.SDK_INT >= 23) {if (!hasBasePhoneAuth()) {this.requestPermissions(authBaseArr, authBaseRequestCode);return;}}}}

权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 

根据URI获取文件真实路径

Uri uri = data.getData();
String filePath = FileUtil.getFilePathByUri(this, uri);
/*** @author : LGQ* @date : 2020/05/04 13* @desc :*/
public class FileUtil {/*** 根据URI获取文件真实路径(兼容多张机型)*/public static String getFilePathByUri (Context context, Uri uri) {if ("content".equalsIgnoreCase(uri.getScheme())) {int sdkVersion = Build.VERSION.SDK_INT;if (sdkVersion >= 19) { // api >= 19return getRealPathFromUriAboveApi19(context, uri);} else { // api < 19return getRealPathFromUriBelowAPI19(context, uri);}} else if ("file".equalsIgnoreCase(uri.getScheme())) {return uri.getPath();}return null;}/*** 适配api19及以上,根据uri获取图片的绝对路径** @param context 上下文对象* @param uri     图片的Uri* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null*/@SuppressLint("NewApi")private static String getRealPathFromUriAboveApi19 (Context context, Uri uri) {String filePath = null;if (DocumentsContract.isDocumentUri(context, uri)) {// 如果是document类型的 uri, 则通过document id来进行处理String documentId = DocumentsContract.getDocumentId(uri);if (isMediaDocument(uri)) { // MediaProvider// 使用':'分割String type = documentId.split(":")[0];String id = documentId.split(":")[1];String selection = MediaStore.Images.Media._ID + "=?";String[] selectionArgs = {id};//Uri contentUri = null;if ("image".equals(type)) {contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;} else if ("video".equals(type)) {contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;} else if ("audio".equals(type)) {contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;}filePath = getDataColumn(context, contentUri, selection, selectionArgs);} else if (isDownloadsDocument(uri)) { // DownloadsProviderUri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));filePath = getDataColumn(context, contentUri, null, null);} else if (isExternalStorageDocument(uri)) {// ExternalStorageProviderfinal String docId = DocumentsContract.getDocumentId(uri);final String[] split = docId.split(":");final String type = split[0];if ("primary".equalsIgnoreCase(type)) {filePath = Environment.getExternalStorageDirectory() + "/" + split[1];}} else {//Log.e("路径错误");}} else if ("content".equalsIgnoreCase(uri.getScheme())) {// 如果是 content 类型的 UrifilePath = getDataColumn(context, uri, null, null);} else if ("file".equals(uri.getScheme())) {// 如果是 file 类型的 Uri,直接获取图片对应的路径filePath = uri.getPath();}return filePath;}/*** 适配api19以下(不包括api19),根据uri获取图片的绝对路径** @param context 上下文对象* @param uri     图片的Uri* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null*/private static String getRealPathFromUriBelowAPI19 (Context context, Uri uri) {return getDataColumn(context, uri, null, null);}/*** 获取数据库表中的 _data 列,即返回Uri对应的文件路径*/private static String getDataColumn (Context context, Uri uri, String selection, String[] selectionArgs) {String path = null;String[] projection = new String[]{MediaStore.Images.Media.DATA};Cursor cursor = null;try {cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);if (cursor != null && cursor.moveToFirst()) {int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);path = cursor.getString(columnIndex);}} catch (Exception e) {if (cursor != null) {cursor.close();}}return path;}/*** @param uri the Uri to check* @return Whether the Uri authority is MediaProvider*/private static boolean isMediaDocument (Uri uri) {return "com.android.providers.media.documents".equals(uri.getAuthority());}/*** @param uri the Uri to check* @return Whether the Uri authority is DownloadsProvider*/private static boolean isDownloadsDocument (Uri uri) {return "com.android.providers.downloads.documents".equals(uri.getAuthority());}private static boolean isExternalStorageDocument (Uri uri) {return "com.android.externalstorage.documents".equals(uri.getAuthority());}
}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/415368.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【洛谷P3389】【模板】高斯消元

题目链接 题目描述 给定一个线性方程组&#xff0c;对其求解 输入输出格式 输入格式&#xff1a; 第一行&#xff0c;一个正整数 n 第二至 n1行&#xff0c;每行 n1 个整数&#xff0c;为a1, a2 .....an​ 和 b&#xff0c;代表一组方程。 输出格式&#xff1a; 共n行&#xff…

微信小程序上传的视频显示封面 我是阿里云oss的实现

我们一般用wx.chooseVideo拍摄视频或从手机相册中选视频&#xff0c;然后上传到后台存储空间。 但是给用户显示视频列表的时候&#xff0c;需要视频封面额。 阿里oss地址&#xff1a;https://help.aliyun.com/document_detail/64555.html?spm5176.11065259.1996646101.searc…

Android 仿微信多张图片选择器,适配android10系统,open failed: EACCES (Permission denied)

实现效果 只需引入模块&#xff0c;比起依赖&#xff0c;更方便自定义 implementation project(:imagepicker) //图片加载 implementation com.github.bumptech.glide:glide:4.11.0 初始化即可使用 private void initImagePicker() {ImagePicker imagePicker ImagePicker.g…

前端学习(2638):读懂代码之登录页login.vue之ref和rules

<template><div class"login-wrap"><div class"ms-login"><div class"ms-title">后台管理系统</div><!--1定义参数类型 2定义路由规则 3使用ref去进行指向 --><el-form :model"param" :rules&…

mongodb save和insert区别

mongodb的save和insert函数都可以向collection里插入数据&#xff0c;但两者是有两个区别&#xff1a; 一、使用save函数里&#xff0c;如果原来的对象不存在&#xff0c;那他们都可以向collection里插入数据&#xff0c;如果已经存在&#xff0c;save会调用update更新里面的记…

P1967 货车运输

P1967 货车运输最大生成树lca并查集 1 #include<iostream>2 #include<cstdio>3 #include<queue>4 #include<algorithm>5 #include<cmath>6 #include<ctime>7 #include<set>8 #include<map>9 #include<stack>10 #include…

前端学习(2640):懂代码之登录页login.vue存入用户信息

<template><div class"login-wrap"><div class"ms-login"><div class"ms-title">后台管理系统</div><!--1定义参数类型 2定义路由规则 3使用ref去进行指向 --><el-form :model"param" :rules&…

js 根据时间生成唯一订单号

一般做唯一编号的时候&#xff0c;可以使用guid或者uuid的包直接生成&#xff0c;但是我希望唯一编号能够反应生成的时间信息&#xff0c;所以就准备使用日期随机值来构造&#xff0c;代码如下&#xff1a; const tradeNo function () {const now new Date()const year now…

(转) 并发处理

1、使用事物 2、使用消息队列 可以基于例如MemcacheQ等这样的消息队列。 比如有100张票可供用户抢&#xff0c;那么就可以把这100张票放到缓存中&#xff0c;读写时不要加锁。 当并发量大的时候&#xff0c;可能有500人左右抢票成功&#xff0c;这样对于500后面的请求可以直接转…

js将字符串 YYMMDDHHmmss 转化为 date类型

微信支付的回调参数time_end为日期字符串。 需求&#xff1a;将20190523101156转化为转换为Date日期格式Thu May 23 2019 10:11:56 GMT0800 (中国标准时间) const str2date (dateString)> {const pattern /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/;return new Dat…

Android 自定义带图标Toast,工具方法,Toast自定义显示时间

带图标Toast工具方法1 public static void show(Context act, String strContent, int iResouce){try {Toast toast new Toast(act);View view LayoutInflater.from(act).inflate(R.layout.layout_dialog_toastok, null);TextView tvContent view.findViewById(R.id.content…

This relative module was not found ./cptable webpack

在使用xlsx库的时候遇到的报错。 This relative module was not found: * ./cptable in ./node_modules/xlsx-style/dist/cpexcel.js记录解决方法&#xff0c;我是使用webpack进行配置的。 在chainWebpack里面增加一行代码&#xff0c;重新编译&#xff0c;即可。 config.ext…

工作155:首页样式调整第二次

<el-card><h1 style"float: left;margin-top: 34px;margin-left: 32px;">我的订单</h1><el-button size"mini" style"float: right;margin-top: 14px;margin-right: 10px;" type"primary" click"ListClick…

关于CaciiEZ端口流量阀值报警的设置

作者:邓聪聪 环境&#xff1a;CactiEZ v10.1 为了更高效的发现问题&#xff0c;在非工作期间&#xff0c;公司的网络可能会出现一些故障&#xff0c;为了及时解决问题&#xff0c;所以做了一个流量监控&#xff0c;并以邮件的方式发送流量异常的端口&#xff0c;以便及时了解状…

微信开发 getUserInfo:fail tunneling socket could not be established, cause=connect ECONNREFUSED

微信开发过程中&#xff0c;突然遇到一个奇怪的问题&#xff1a; 解决办法&#xff1a; 找到开发工具中 “工具 - 设置 - 代理设置”&#xff0c;选择即可不使用任何代理。

glide工具类。加载显示原图片,显示圆角图片,gif图标显示

依赖 //支持gif 的控件 implementation pl.droidsonroids.gif:android-gif-drawable:1.2.1 工具方法 private void updateGifLoopOne(GifImageView gif) {try { // 3、动画启动说明 // a、场景GIF每换一次页面&#xff0c;重新动画一次&#xff0c;每个…

Socket常用语法与socketserver实例

1》Socket相关&#xff1a; 1>Socket Families(地址簇): socket.AF_UNIX   本机进程间通信 socket.AF_INET   IPV4  socket.AF_INET6   IPV6 2>Socket Types: socket.SOCK_STREAM   #for tcp socket.SOCK_DGRAM   #for udp  socket.SOCK_RAW …

重新记录一下微信后台的配置

1、打开开发的基本配置&#xff0c;成为开发者 2、启用开发者密码 3、看一下自己的公众号id 4、记录自己的AppID、AppSecret

vue2.0 如何自定义组件(vue组件的封装)

一、前言 之前的博客聊过 vue2.0和react的技术选型&#xff1b;聊过vue的axios封装和vuex使用。今天简单聊聊 vue 组件的封装。 vue 的ui框架现在是很多的&#xff0c;但是鉴于移动设备的复杂性&#xff0c;兼容性问题突出。像 Mint-UI 等说实话已经很不错了&#xff0c;但是坑…