首页 > 其他分享 >Android从相册、照相机选择图片(支持4.4+,KIKAT以上)

Android从相册、照相机选择图片(支持4.4+,KIKAT以上)

时间:2023-07-28 10:37:38浏览次数:40  
标签:4.4 int cursor bmp Intent KIKAT new Android intent


开发都会遇到从手机的相册和照相机选择图片的功能,下面是一段通用的代码,用来选择手机中的图片,以后用的时候,直接调用就可以了。


使用到的类属性

public final static int CONSULT_DOC_PICTURE = 1000;
public final static int CONSULT_DOC_CAMERA = 1001;
private int SELECT_PICTURE = 0;
private int SELECT_CAMERA = 1;
private Bitmap bmp;
private Uri outputFileUri;
//从相册或照相机选择出的文件,可以用来判断是否上传
File selectImg;

弹出选择对话框

protected void createSelectImageDialog() {
  CharSequence[] items = { "相册", "照相机" };
  new AlertDialog.Builder(this).setTitle("选择图片来源").setItems(items, new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int which) {
    if (which == SELECT_PICTURE) {
     Intent intent = new Intent();
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
      intent.setAction(Intent.ACTION_GET_CONTENT);
     }
     else {
      intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
      intent.addCategory(Intent.CATEGORY_OPENABLE);
     }
     intent.setType("image/*");
     startActivityForResult(Intent.createChooser(intent, "选择图片"), CONSULT_DOC_PICTURE);
    } else {
     File file = new File(Environment.getExternalStorageDirectory(), "avator.jpg");
     outputFileUri = Uri.fromFile(file);
     Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
     intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
     startActivityForResult(intent, CONSULT_DOC_CAMERA);
    }
   }
  }).create().show();
 }

获取返回的数据,因为使用的不是return-data,所以返回的是uri需要自己去查询一下真实路径

@SuppressLint("NewApi")
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == CONSULT_DOC_PICTURE) {

   if(data == null){
    return;
   }
   if (bmp != null)// 如果不释放的话,不断取图片,将会内存不够
    bmp.recycle();
   if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT){
    Uri contentUri = data.getData();
    String wholeID = DocumentsContract.getDocumentId(contentUri);
    String id = wholeID.split(":")[1];
    String[] column = { MediaStore.Images.Media.DATA };
    String sel = MediaStore.Images.Media._ID + "=?";
    Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, column,
      sel, new String[] { id }, null);
    int columnIndex = cursor.getColumnIndex(column[0]);
    if (cursor.moveToFirst()) {
     String path = cursor.getString(columnIndex);
     bmp = BitmapFactory.decodeFile(path);
     avator.setImageBitmap(bmp);
     selectImg = new File(path);
    }
    cursor.close();
   }else{
    Uri uri = data.getData();
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = this.getContentResolver().query(uri, proj, // Which
      null, // WHERE clause; which rows to return (all rows)
      null, // WHERE clause selection arguments (none)
      null); // Order-by clause (ascending by name)
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String path = cursor.getString(column_index);
    bmp = BitmapFactory.decodeFile(path);
    avator.setImageBitmap(bmp);
    selectImg = new File(path);
    cursor.close();
   }
  } else if (requestCode == CONSULT_DOC_CAMERA) {
   bmp = BitmapFactory.decodeFile(outputFileUri.getPath());
   avator.setImageBitmap(bmp);
   selectImg = new File(outputFileUri.getPath());
  } else {
   Toast.makeText(this, "请重新选择图片", Toast.LENGTH_SHORT).show();
  }
 }

调用的时候只需要在触发事件中 直接调用createSelectImageDialog方法

选择出来的图片是原始图片,图片很大,不适于上传功能


标签:4.4,int,cursor,bmp,Intent,KIKAT,new,Android,intent
From: https://blog.51cto.com/u_13912333/6879021

相关文章

  • AndroidAnnotations 使用在library项目中出现无法找到R文件下资源索引的错误
    AndroidAnnotations使用在library项目中出现无法找到R文件下资源索引的错误使用AndroidAnnotations(以下简称AA)已经有一段时间了,挺好用的,基本上完全可以满足Android开发需要,可以简化代码,所以现在在岗编写的所有的项目都是基于AA实现的。AA现在最新版本为3.2官方地址:http://android......
  • Kotlin 踩坑日记(六)Android studio 3.0.0 Canary 4 Instant Run
    前言宁夏的特色假日,开斋节放了5天,今天回来上班。放假前,Androidstudio3.0发布了Canary4的升级,因为即将放假,所以就没有升级,节后上班第一天,就安排升级并且试用一下。DebugApk找不到Application类没有别的问题,只是在InstantRun环境下,找不到App的Application类,应用安装成功后,......
  • Android 人脸识别 MTCNN Kotlin实现
    前言看见网上有一个MTCNN的Java实现,闲来无事,把Java实现用Koltin重写了一下,主要是针对使用MTCNN来识别人脸。不想罗嗦看的,可以直接去我的github上下载已经写好的demo。https://github.com/ChineseLincoln/AndroidFaceNet文章目录前言人脸识别tensorflowAndroid依赖配置MTCNN......
  • Android-定义和获取字符串资源
    resource->values->strings.xml里定义字符串定义单字符串:<stringname="app_name">abc123</string>定义字符串数组:<string-arrayname="map_style_array"><item>MAPBOX_STREETS</item><item>OUTDO......
  • 17 位谷歌 Android 开发专家是如何看待 Kotlin 的?
    译者简介:ASCE1885,《Android高级进阶》作者。*微信公众号:asce1885*小密圈:Android高级进阶,详情见这篇文章。*Github,简书,微博,原文链接:https://antonioleiva.com/google-kotlin/,由于Markdown对图片的排版存在限制,因此为了保证排版的美观,本文对作者介绍部分进行截图,不做另......
  • Android-单例模式
    单例模式意图:这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。 publicclassSingleton{privatestaticSingletoninstance=newSingleton();......
  • Android studio id 'org.jetbrains.kotlin.android' version '1.7.20' apply fals
    如何实现"Androidstudioid'org.jetbrains.kotlin.android'version'1.7.20'applyfalse"在Android开发中,AndroidStudio是一个常用的集成开发环境(IDE),用于开发Android应用程序。在AndroidStudio中,我们可以使用Kotlin作为一种更现代化的编程语言。本文将向刚入行的开发者介绍......
  • Android studio JavaVersion.VERSION_1_8
    在AndroidStudio中配置Java版本为1.8作为一名经验丰富的开发者,我将指导你如何在AndroidStudio中配置Java版本为1.8。下面是整个流程的步骤:步骤操作1打开项目2打开ProjectStructure3配置Java版本4应用更改现在,让我们一步一步地详细说明每个步骤需要......
  • Android studio DerInputStream.getLength(): lengthTag=109, too big.Failed to
    AndroidStudio:解决DerInputStream.getLength():lengthTag=109,toobig.Failedto的问题简介在使用AndroidStudio开发Android应用程序时,你可能会遇到DerInputStream.getLength():lengthTag=109,toobig.Failedto的错误。该错误通常发生在尝试使用包含较大数据的......
  • Android shell模拟物理按键
    Androidshell模拟物理按键在Android开发中,有时候我们需要模拟物理按键的操作,例如模拟点击返回键、Home键等。Android提供了一个能够在命令行中模拟按键操作的工具——input。input命令简介input命令是Android系统中的一个工具,用于模拟按键事件。通过使用不同的参数,我们可以模拟......