>>>>>>>>>>>", "获取图片旋转的角度报错:" + e.message)调用上面的方法,照相成功之后返回的图片只有300多像素,是被压缩过的,我们需要获取原始图片。4、依赖的xml文件,创建file_paths.xml到res的xml目录。//根据业务逻辑来处理这个photoRotationBitmap。3、定义ImageFileProvider。//得到旋转后的图片。5、UI那边实现这个方法。">
赞
踩
问题描述:
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) activity.startActivityForResult(intent,100)
调用上面的方法,照相成功之后返回的图片只有300多像素,是被压缩过的,我们需要获取原始图片。
改进如下:
1、启动照相机之前,增加MediaStore.EXTRA_OUTPUT参数配置:
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) intent.putExtra(MediaStore.EXTRA_OUTPUT, getImageUri()) activity.startActivityForResult(intent,100)
2、getImageUri的实现如下:
public static Uri getImageUri() { File outFile = new File(context.getExternalCacheDir().getPath(), "image_test.png"); Uri contentUri = FileProvider.getUriForFile( context, context.getPackageName() + ".ImageFileProvider", outFile ); return contentUri; }
3、定义ImageFileProvider
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.ImageFileProvider" android:grantUriPermissions="true" android:exported="false"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
4、依赖的xml文件,创建file_paths.xml到res的xml目录
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="external_files" path="." /> <external-files-path name="external_files" path="." /> <cache-path name="cache_files" path="." /> <files-path name="files" path="." /> <external-path name="my_images" path="."/> </paths>
5、UI那边实现这个方法
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { if (resultCode != Activity.RESULT_OK) { return; } try { Uri uri = getImageUri(); Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri); InputStream inputStream = context.getContentResolver().openInputStream(uri); //获取旋转角度 float photoRotation = getPhotoRotation(inputStream); //得到旋转后的图片 Bitmap photoRotationBitmap = rotate(bitmap, photoRotation); //根据业务逻辑来处理这个photoRotationBitmap
//todo
} catch (Exception e) { e.printStackTrace(); }
}
6、getPhotoRotation定义如下:
fun getPhotoRotation(inputStream: InputStream): Float { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val exifInterface = ExifInterface(inputStream) val orientation = exifInterface.getAttributeInt( ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL ) return when (orientation) { ExifInterface.ORIENTATION_ROTATE_90 -> 90f ExifInterface.ORIENTATION_ROTATE_180 -> 180f ExifInterface.ORIENTATION_ROTATE_270 -> 270f else -> 0f } } } catch (e: java.lang.Exception) { LogUtil.e(">>>>>>>>>>>>", "获取图片旋转的角度报错:" + e.message) } return 0f }
7、rotate方法定义如下:
fun rotate(rawBitmap: Bitmap, degree: Float): Bitmap { val matrix = Matrix() matrix.postRotate(degree) return Bitmap.createBitmap(rawBitmap, 0, 0, rawBitmap.width, rawBitmap.height, matrix, true) }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。