Android实现拍照及图片裁剪(6.0以上权限处理及7.0以上文件管理)

Android实现拍照及图片裁剪(6.0以上权限处理及7.0以上文件管理),第1张

概述最近做项目中涉及到了图片相关功能,在使用安卓6.0手机及7.1手机拍照时,遇到了因权限及文件管理导致程序崩溃等问题。

最近做项目中涉及到了图片相关功能 ,在使用安卓6.0手机及7.1手机拍照时,遇到了因权限及文件管理导致程序崩溃等问题。
 刚好把功能修改完,把代码简单地贴一下,方便以后使用。

―-主界面 代码 ――

public class MainActivity extends AppCompatActivity {  //拍照按钮  private button take_photo;  //显示裁剪后的图片  private ImageVIEw photo_iv;  private static final int PERMISSIONS_FOR_TAKE_PHOTO = 10;  //图片文件路径  private String picPath;  //图片对应Uri  private Uri photoUri;  //拍照对应RequestCode  public static final int SELECT_PIC_BY_TACK_PHOTO = 1;  //裁剪图片  private static final int CROP_PICTURE = 3;  @OverrIDe  protected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.activity_main);    take_photo = (button) findVIEwByID(R.ID.take_photo);    photo_iv = (ImageVIEw) findVIEwByID(R.ID.photo_iv);    take_photo.setonClickListener(new VIEw.OnClickListener() {      @OverrIDe      public voID onClick(VIEw vIEw) {        //小于6.0版本直接 *** 作        if (Build.VERSION.SDK_INT < 23) {          takePictures();        } else {          //6.0以后权限处理          permissionForM();        }      }    });  }  @OverrIDe  protected voID onActivityResult(int requestCode,int resultCode,Intent data) {    super.onActivityResult(requestCode,resultCode,data);    if (resultCode == Activity.RESulT_OK) {      if (requestCode == SELECT_PIC_BY_TACK_PHOTO) {        String[] pojo = {MediaStore.Images.Media.DATA};        Cursor cursor = managedquery(photoUri,pojo,null,null);        if (cursor != null) {          int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);          cursor.movetoFirst();          picPath = cursor.getString(columnIndex);          if (Build.VERSION.SDK_INT < 14) {            cursor.close();          }        }        if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {          photoUri = Uri.fromfile(new file(picPath));          if (Build.VERSION.SDK_INT > 23) {            photoUri = fileProvIDer.getUriForfile(this,"com.innopro.bamboo.fileprovIDer",new file(picPath));            cropForN(picPath,CROP_PICTURE);          } else {            startPhotoZoom(photoUri,CROP_PICTURE);          }        } else {          //错误提示        }      }      if (requestCode == CROP_PICTURE) {        if (photoUri != null) {          Bitmap bitmap = BitmapFactory.decodefile(picPath);          if (bitmap != null) {            photo_iv.setimageBitmap(bitmap);          }        }      }    }  }  /**   * 拍照获取图片   */  private voID takePictures() {    //执行拍照前,应该先判断SD卡是否存在    String SDState = Environment.getExternalStorageState();    if (SDState.equals(Environment.MEDIA_MOUNTED)) {      Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);      ContentValues values = new ContentValues();      photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);      intent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);      startActivityForResult(intent,SELECT_PIC_BY_TACK_PHOTO);    } else {      Toast.makeText(this,"手机未插入内存卡",Toast.LENGTH_LONG).show();    }  }  /**   * 图片裁剪,参数根据自己需要设置   *   * @param uri   * @param REQUE_CODE_CROP   */  private voID startPhotoZoom(Uri uri,int REQUE_CODE_CROP) {    int dp = 500;    Intent intent = new Intent("com.androID.camera.action.CROP");    intent.setDataAndType(uri,"image/*");    // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪    intent.putExtra("crop","true");    intent.putExtra("scale",true);// 去黑边    intent.putExtra("scaleUpIfNeeded",true);// 去黑边    // aspectX aspectY 是宽高的比例    intent.putExtra("aspectX",4);//输出是X方向的比例    intent.putExtra("aspectY",3);    intent.putExtra("outputX",600);//输出X方向的像素    intent.putExtra("outputY",450);    intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());    intent.putExtra("noFaceDetection",true);    intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);    intent.putExtra("return-data",false);//设置为不返回数据    startActivityForResult(intent,REQUE_CODE_CROP);  }  /**   * 7.0以上版本图片裁剪 *** 作   *   * @param imagePath   * @param REQUE_CODE_CROP   */  private voID cropForN(String imagePath,int REQUE_CODE_CROP) {    Uri cropUri = getimageContentUri(new file(imagePath));    Intent intent = new Intent("com.androID.camera.action.CROP");    intent.setDataAndType(cropUri,"image/*");    intent.putExtra("crop","true");    //输出是X方向的比例    intent.putExtra("aspectX",4);    intent.putExtra("aspectY",3);    // outputX outputY 是裁剪图片宽高    intent.putExtra("outputX",600);    intent.putExtra("outputY",450);    intent.putExtra("scale",true);    intent.putExtra("return-data",false);    intent.putExtra(MediaStore.EXTRA_OUTPUT,cropUri);    intent.putExtra("outputFormat",true);    startActivityForResult(intent,REQUE_CODE_CROP);  }  private Uri getimageContentUri(file imagefile) {    String filePath = imagefile.getabsolutePath();    Cursor cursor = getContentResolver().query(        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,new String[]{MediaStore.Images.Media._ID},MediaStore.Images.Media.DATA + "=? ",new String[]{filePath},null);    if (cursor != null && cursor.movetoFirst()) {      int ID = cursor.getInt(cursor          .getColumnIndex(MediaStore.MediaColumns._ID));      Uri baseUri = Uri.parse("content://media/external/images/media");      return Uri.withAppendedpath(baseUri,"" + ID);    } else {      if (imagefile.exists()) {        ContentValues values = new ContentValues();        values.put(MediaStore.Images.Media.DATA,filePath);        return getContentResolver().insert(            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);      } else {        return null;      }    }  }  /**   * 安卓6.0以上版本权限处理   */  private voID permissionForM() {    if (ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {      ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},PERMISSIONS_FOR_TAKE_PHOTO);    } else {      takePictures();    }  }  @OverrIDe  public voID onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {    if (requestCode == PERMISSIONS_FOR_TAKE_PHOTO) {      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {        takePictures();      }      return;    }    super.onRequestPermissionsResult(requestCode,permissions,grantResults);  }}

C主界面布局――C

<?xml version="1.0" enCoding="utf-8"?><androID.support.constraint.ConstraintLayout 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"  tools:context="com.innopro.improve.MainActivity">  <button    androID:ID="@+ID/take_photo"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:text="拍照"    androID:textSize="18sp"    app:layout_constraintleft_toleftOf="parent"    app:layout_constraintRight_toRightOf="parent"    app:layout_constrainttop_totopOf="parent" />  <ImageVIEw    androID:ID="@+ID/photo_iv"    androID:layout_wIDth="wrap_content"    androID:layout_height="wrap_content"    androID:src="@mipmap/ic_launcher"    app:layout_constraintleft_toleftOf="parent"    app:layout_constraintRight_toRightOf="parent"    app:layout_constrainttop_toBottomOf="@ID/take_photo" /></androID.support.constraint.ConstraintLayout>

CAndroIDManifest.xml添加provIDer――C

   <provIDer      androID:name="androID.support.v4.content.fileProvIDer"      androID:authoritIEs="com.innopro.improve.fileprovIDer"      androID:exported="false"      androID:grantUriPermissions="true">      <Meta-data        androID:name="androID.support.file_PROVIDER_PATHS"        androID:resource="@xml/file_paths" />    </provIDer>

C资源文件下添加xml文件夹及file_paths文件――C

<?xml version="1.0" enCoding="utf-8"?><resources>  <paths>    <external-path      name="camera_photos"      path="" />  </paths></resources>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android实现拍照及图片裁剪(6.0以上权限处理及7.0以上文件管理)全部内容,希望文章能够帮你解决Android实现拍照及图片裁剪(6.0以上权限处理及7.0以上文件管理)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1144063.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存