国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android實現拍照及圖片裁剪(6.0以上權限處理及7.0以上文件管理)

2019-10-22 18:25:24
字體:
來源:轉載
供稿:網友

最近做項目中涉及到了圖片相關功能 ,在使用安卓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, 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", Bitmap.CompressFormat.JPEG.toString());    intent.putExtra("noFaceDetection", 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);  }}

–主界面布局——–

<?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>

–AndroidManifest.xml添加provider——–

   <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>

–資源文件下添加xml文件夾及file_paths文件——–

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 得荣县| 桐柏县| 丰镇市| 奈曼旗| 合川市| 香河县| 凤阳县| 永安市| 邵阳县| 宾川县| 万载县| 东乡县| 乌兰浩特市| 阜新市| 黄骅市| 天津市| 广饶县| 洛隆县| 洛川县| 琼中| 临邑县| 息烽县| 苏尼特左旗| 达州市| 华安县| 孙吴县| 云梦县| 松阳县| 体育| 古丈县| 濉溪县| 阜平县| 名山县| 新野县| 报价| 金塔县| 中江县| 保靖县| 大化| 长顺县| 安国市|