android判断相机图片朝向的简单方法
android应用里使用相机图片时必须要考虑的一个问题就是图片朝向,只有判断对朝向才能调整图片从而更好的展现。本文将介绍一种通过ExifInterface判断图片朝向的方法!
上代码:
/** * * 利用给定路径下的图片设置ImageView * * @param imgPath 手机图片文件路径 * @param imgView 需要设置的ImageView */ public void setImg(String imgPath, ImageView imgView) { File file = new File(imgPath); if (file.exists() && file.canRead()) { // -------1.图片缩放-------- // 手机屏幕信息 DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); int dw = metric.widthPixels; // 屏幕宽 int dh = metric.heightPixels; // 屏幕高 // 加载图像,只是为了获取尺寸 BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 设置之后可以获取尺寸信息 Bitmap bitmap = BitmapFactory.decodeFile(imgPath, options); // 计算水平和垂直缩放系数 int heightRatio = (int) Math.ceil(options.outHeight / (float) dh); int widthRatio = (int) Math.ceil(options.outWidth / (float) dw); // 判断哪个大 if (heightRatio > 1 && widthRatio > 1) { if (heightRatio > widthRatio) { options.inSampleSize = heightRatio; } else { options.inSampleSize = widthRatio; } } // 图片缩放 options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeFile(imgPath, options); // -------2.判断图片朝向-------- try { ExifInterface exif = new ExifInterface(imgPath); int degree = 0; // 图片旋转角度 if (exif != null) { int orientation = exif.getAttributeInt( ExifInterface.TAG_ORIENTATION, -1); if (orientation != -1) { switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; default: break; } } } if (degree != 0) { // 图片需要旋转 int width = bitmap.getWidth(); int height = bitmap.getHeight(); Matrix matrix = new Matrix(); matrix.preRotate(degree); Bitmap mRotateBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true); imgView.setImageBitmap(mRotateBitmap); } else { imgView.setImageBitmap(bitmap); } } catch (IOException e) { } } }
本代码包含两大功能:
1. 图片缩放:原始图片一般比较大,经过缩小才能使用;
2. 图片旋转:由于用户拍照时手机角度不同,所得照片可能需要旋转。
以上这篇android判断相机图片朝向的实现方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Material Design系列之Behavior实现支付密码弹窗和商品属性选择效果
这篇文章主要为大家详细介绍了Material Design系列之Behavior实现支付密码弹窗和商品属性选择效果,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-09-09Android应用中使用TabHost组件继承TabActivity的布局方法
这篇文章主要介绍了Android应用中使用TabHost组件继承TabActivity的布局方法,文中分别介绍了以Activity和以布局文件进行布局的方式,需要的朋友可以参考下2016-04-04Android开发之开关按钮控件ToggleButton简单用法示例
这篇文章主要介绍了Android开发之开关按钮控件ToggleButton简单用法,结合实例形式分析了Android开关按钮控件ToggleButton的相关xml布局与调用操作技巧,需要的朋友可以参考下2017-12-12解决Android自定义view获取attr中自定义颜色的问题
这篇文章主要介绍了Android自定义view获取attr中自定义颜色的问题解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2020-12-12Android RecyclerView仿新闻头条的频道管理功能
这篇文章主要介绍了Android RecyclerView仿新闻头条的频道管理功能,需要的朋友可以参考下2017-06-06深入理解TextView实现Rich Text--在同一个TextView设置不同字体风格
本篇文章是对Android中在同一个TextView中设置不同的字体风格进行了详细的分析介绍,需要的朋友参考下2013-05-05
最新评论