Android实现拍照及图片裁剪(6.0以上权限处理及7.0以上文件管理)
作者:迟做总比不做强 发布时间:2022-05-19 09:18:14
标签:android6.0,权限,拍照
最近做项目中涉及到了图片相关功能 ,在使用安卓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>
来源:http://blog.csdn.net/true100/article/details/78285270
0
投稿
猜你喜欢
- 什么是面向对象Java语言是一个纯面向对象的语言,面向对象的语言不仅只有Java,包括C++,PHP等面向对象的编程思想简称 OOP(Obj
- 如题,主要使用AsReadOnly这个方法就可以了List<int> a = new List<int> {1, 2
- 在spring的注解 @RequestMapping 之下可以直接获取 HttpServletRequest 来获得诸如request he
- 这篇文章主要介绍了java 对象参数去空格方式代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋
- 因为最近用报表导出比较多,所有就提成了一个工具类,本工具类使用的场景为 根据提供的模板来导出Excel报表并且可根据提供的模板S
- Java程序设计 图形用户界面 【十】复选框复选框JCheckBoxJCheckBox类方法作用public JCheckBox(Icon
- IDEA版本:2020.3具体步骤一、开启IDEA的自动编译【静态】1.File->Settings。2.直接搜索Compiler,选
- 本文实例讲述了Java实现的求解经典罗马数字和阿拉伯数字相互转换问题。分享给大家供大家参考,具体如下:古罗马帝国开创了辉煌的人类文明,但他们
- 这些天忙着刷题,又怕遗忘了spring boot, 所以抽出一点时间折腾折腾,加深点印象。 spring boot 的文件上传与 sprin
- 前言一般在c++中没有使用的变量会有警告,C#中也有,在QT中我们利用Q_UNSED可以直接消除这些警告,那么我们在C#中该如何做才能消除这
- Java本身都是值传递式的调用,对于对象传递的是地址值。给地址值重新赋值等于重新指向,不会影响外层。而且这里Integer对象也有特殊性。其
- Mybatis属于半自动ORM,在使用这个框架中,工作量最大的就是书写Mapping的映射文件,由于手动书写很容易出错,我们可以利用Myba
- utf-8转unicode public static String utf8ToUnicode(String inStr) {  
- 新建一个表:create table abc(id int IDENTITY(1,1) NOT NULL,name nvarchar(100
- 实践过程效果代码/** * https://zhima.blog.csdn.net/ */public partial class Form
- 随着C#的发展,该语言内容不断丰富,开发变得更加方便快捷,C# 的锋利尽显无疑。C# 语言从诞生起就是强类型语言,这一性质到今天不曾改变,我
- 1、在ActionSupport中有一个validate()方法,这个方法是验证方法,它会在execute()方法执行之前执行,所以能够起到
- SpringBoot整合Mybatis自定义 * 不起作用Mybatis插件生效的方式:1. 原始的读取mybatis-config.xml
- 一、简介当我们没有在子类构造函数中写上 base(),默认会先调用父类中无参的构造函数,再调用子类。当在有参构造函数后写上base时,只调用
- 在HotSpot虚拟机中,对象在内存中存储的布局可以分为三块区域:对象头(Header)、实例数据(Instance Data)和对齐填充(