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


猜你喜欢
- 前言Java中的原生反射库虽然方法不多,但写起来却非常繁琐, 比如:public static <T> T create(Htt
- spring和mybatis整合整合思路需要spring通过单例方式管理SqlSessionFactory。spring和mybatis整合
- maven依赖及一些配置这里主要是搭建项目常用到的maven依赖以及搭建项目会需要用到的一些配置文件,可能下面这些依赖还不是很全,但是应该会
- 前言此系统为博主大一上学期C语言课程设计的大作业,由于当时初步接触C语言,现在来看程序写的太烂了,简直不忍直视……但是还是想通过博客的形式记
- 重载1.构造器的重载因为构造器的名字必须与类名相同,所以同一个类的所有构造器名肯定相同,构成重载;为了让系统能区分不同的构造器,多个构造器的
- WCF实例(带步骤) <xmlnamespace prefix ="o" ns ="urn:schema
- * 的实现使用的模式:代理模式。代理模式的作用是:为其他对象提供一种代理以控制对这个对象的访问。类似租房的中介。两种 * :(1)jd
- AuthenticationProvider解析首先进入到AuthenticationProvider源码中可以看到它只是个简单的接口里面也
- 在redirect重定向的时候携带参数问题SpringMVC 中常用到 redirect来实现重定向。但使用场景各有需求,如果只是简单的页面
- 1.概述1、Spring 是轻量级的开源的 JavaEE 框架2、 Spring 可以解决企业应用开发的复杂性3、Spring 有两个核心部
- 一、简介相信大家用eclipse上的模拟器会觉得很慢很卡,这里给大家介绍个好东西安卓模拟器genymotion。了解更多,可到此网站http
- Vector实现班级信息管理系统,供大家参考,具体内容如下代码如下:import java.util.*;public class Demo
- 1 前言有时候我们的程序中要提供可以使用代理访问网络,代理的方式包括http、https、ftp、socks代理。比如在IE浏览器设置代理。
- 本文实例讲述了C#将布尔类型转换成字节数组的方法。分享给大家供大家参考。具体如下:byte[] b = null;b = BitConver
- Java 8的18个常用日期处理一、简介伴随lambda表达式、streams以及一系列小优化,Java 8 推出了全新的日期时间API。J
- 背景 我们知道在.NET Framework中存在四种常用的定时器,他们分别是:1 两个是通用的多线程定时器:Syste
- 发布:一个对象是使它能够被当前范围之外的代码所引用:常见形式:将对象的的引用存储到公共静态域;非私有方法中返回引用;发布内部类实例,包含引用
- 本文为大家分享了AForge实现C#摄像头视频录制功能的具体方法,供大家参考,具体内容如下1. 概述最近由于兴趣学习了下在C#上使用AFor
- 首先我们在项目中导入这个框架:implementation 'com.mcxiaoke.volley:library:1.0.19&
- 现在很多的javascript控件,非常的不错,其中step就是一个,如下图所示:那么如何用C#来实现一个step控件呢?先定义一个Step