Android Tool Class ImgUtil Select Camera and System Album

  • 2021-10-16 02:48:34
  • OfStack

In this paper, we share the specific codes of Android camera and system photo album for your reference. The specific contents are as follows

Description:

Android Select Camera and System Album

Code:

1. Open the system camera and system photo album tool class


package com.gxjl.pe.gxjlpesdk.util;
 
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.widget.Toast;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * 图片工具类
 * Created by xiaoshuai on 2018/8/17.
 */
 
public class ImgUtil {
 public static final int TAKE_PHOTO = 1;//拍照
 public static final int CHOOSE_PHOTO = 2;//选择相册
 public static final int REQUEST_CODE_CAMERA = 3;//相机权限请求
 public static final int REQUEST_CODE_ALBUM = 4;//相册权限请求
 public static Uri imageUri;//相机拍照图片保存地址
 
 /**
  * 选择图片,从图库、相机
  *
  * @param activity 上下文
  */
 public static void choicePhoto(final Activity activity) {
  //采用的是系统Dialog作为选择弹框
  new AlertDialog.Builder(activity).setTitle("上传头像")//设置对话框标题
    .setPositiveButton("拍照", new DialogInterface.OnClickListener() {//添加确定按钮
     @Override
     public void onClick(DialogInterface dialog, int which) {
      if (Build.VERSION.SDK_INT >= 23) {//检查相机权限
       ArrayList<String> permissions = new ArrayList<>();
       if (activity.checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
        permissions.add(Manifest.permission.CAMERA);
       }
 
       if (permissions.size() == 0) {//有权限,跳转
        //打开相机-兼容7.0
        openCamera(activity);
       } else {
        activity.requestPermissions(permissions.toArray(new String[permissions.size()]), REQUEST_CODE_CAMERA);
       }
      } else {
       //打开相机-兼容7.0
       openCamera(activity);
      }
     }
    }).
    setNegativeButton("系统相册", new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
      //如果有权限申请,请在Activity中onRequestPermissionsResult权限返回里面重新调用openAlbum()
      if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
       ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_ALBUM);
      } else {
       openAlbum(activity);
      }
     }
    }).show();//在按键响应事件中显示此对话框
 }
 
 /**
  * 打开相机
  * 兼容7.0
  *
  * @param activity
  */
 public static void openCamera(Activity activity) {
  // 创建File对象,用于存储拍照后的图片
  File outputImage = new File(activity.getExternalCacheDir(), "output_image.jpg");
  try {
   if (outputImage.exists()) {
    outputImage.delete();
   }
   outputImage.createNewFile();
  } catch (IOException e) {
   e.printStackTrace();
  }
  if (Build.VERSION.SDK_INT < 24) {
   imageUri = Uri.fromFile(outputImage);
  } else {
   //Android 7.0系统开始 使用本地真实的Uri路径不安全,使用FileProvider封装共享Uri
   //参数2:fileprovider绝对路径 com.dyb.testcamerademo:项目包名
   imageUri = FileProvider.getUriForFile(activity, "com.mandaotech.ewallet.fileprovider", outputImage);
  }
  // 启动相机程序
  Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
  intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
  activity.startActivityForResult(intent, TAKE_PHOTO);
 }
 
 /**
  * 打开图库
  * @param activity
  */
 public static void openAlbum(Activity activity) {
  //调用系统图库的意图
  Intent choosePicIntent = new Intent(Intent.ACTION_PICK, null);
  choosePicIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
  activity.startActivityForResult(choosePicIntent, CHOOSE_PHOTO);
 
  //打开系统默认的软件
  //Intent intent = new Intent("android.intent.action.GET_CONTENT");
  //intent.setType("image/*");
  //activity.startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
 }
 
 /**
  * 得到byte[]
  * 这里对传入的图片Uri压缩到1M以内,并转换为byte[]后返回
  *
  * @param activity 上下文
  * @param uri  传入图片的Uri
  * @return byte[]
  */
 public static byte[] getImgByteFromUri(Activity activity, Uri uri) throws IOException {
  Bitmap bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);//100表示不压缩,直接放到out里面
  int options = 90;//压缩比例
  while (out.toByteArray().length / 1024 > 200) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
   out.reset(); // 重置baos即清空baos
   bitmap.compress(Bitmap.CompressFormat.JPEG, options, out);// 这里压缩options%,把压缩后的数据存放到baos中
   options -= 10;// 每次都减少10
  }
  byte[] bs = out.toByteArray();
 
  return bs;
 }
 
}

Camera selection: The fixed address is adopted to select a large picture. The upper code block is adapted to 7.0, because it is unsafe for Android 7.0 system to start using the local real Uri path, and FileProvider is used to encapsulate and share Uri. Among them, android: name, exported, android: grantUriPermissions have fixed values, and android: authorities has the values of "Own Project Package Name". fileprovider.

2. Apply for permission confirmation

Click Apply Permission in the tool class to check whether the user agrees with the permission in Activity


@Override
 public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
  switch (requestCode) {
   case REQUEST_CODE_ALBUM:// Album storage permissions 
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
     ImgUtil.openAlbum(this);
    } else {
     UiUtil.showToast(this, " Selecting a gallery requires permission ");
    }
    break;
   case REQUEST_CODE_CAMERA:// Camera photo authority 
    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {// Allow 
     ImgUtil.openCamera(OcrHandReviewActivity.this);
    } else {// Reject 
     UiUtil.showToast(this, " Only agree to camera permissions , To use the code scanning function ");
    }
    break;
   default:
  }
 }

3. Put back the camera and photo album

Get photos and selected pictures in activity


// Camera, photo album, cut   Return 
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
 
  // Return correctly 
  if (resultCode == RESULT_OK) {
   switch (requestCode) {
    case ImgUtil.TAKE_PHOTO:// Camera return 
     Log.e(" Return to camera ", ImgUtil.imageUri.toString());
  
  GlideApp.with(ElecIdPAActivity.this)
        .load(ImgUtil.imageUri)
        .skipMemoryCache(true)
        .diskCacheStrategy( DiskCacheStrategy.NONE )
        .into(iv_zhengmain_photo);
     break;
    case ImgUtil.CHOOSE_PHOTO:// Album return 
     try {
      if (data != null) {
       // Album return 
       Uri uri = data.getData();
       Log.e(" Return to Album ", uri.toString());
  
  GlideApp.with(ElecIdPAActivity.this)
   .load(uri)
   .skipMemoryCache(true)
   .diskCacheStrategy( DiskCacheStrategy.NONE )
   .into(iv_zhengmain_photo);
      }
     } catch (Exception e) {
      e.printStackTrace();
      UiUtil.showToast(this, " Picture selection failed ");
     }
     break;
   }
  } else {
   UiUtil.showToast(this, " Picture selection failed ");
  }
 }

4. AndroidManifest. xml Authority Statement


<!-- Get sd Card write permissions, used for file upload and download -->
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
 <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
 <!-- Allow to read mobile phone status -->
 <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
 <!--  Camera permissions  -->
 <uses-permission android:name="android.permission.CAMERA"/>
 <uses-permission android:name="android.permission.VIBRATE"/>
 <uses-permission android:name="android.permission.FLASHLIGHT"/>
 
<application
 
 <!--7.0 Camera permissions -->
  <provider
   android:name="android.support.v4.content.FileProvider"
   android:authorities="com.dyb.testcamerademo.fileprovider"
   android:exported="false"
   android:grantUriPermissions="true">
   <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/file_paths"/>
  </provider>

5. file_paths. xml

The file name @ xml/in android: resource= "@ xml/file_paths" can be named at will, but it is used in all normalization.
Under xml package (create a new package xml under res, and then create a new file_paths. xml file under xml)

* file_paths. xml source


<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
 
 <!--
 name The value of the property can be written at will , Alias 
 path Property indicates the specific location of the share, and setting null means that the whole SD Card sharing 
  -->
 <paths>
  <external-path
   name="camera_photos"
   path=""/>
 </paths>
</paths>

Related articles: