android摄像头方向与屏方向,Android通过ExifInterface判断Camera图片方向的方法

Android的Camera相关应用开发中,有一个必须搞清楚的知识点,就是Camera的预览方向和拍照方向

图像的Sensor方向:手机Camera的图像数据都是来自于摄像头硬件的图像传感器(Image Sensor),这个Sensor被固定到手机之后是有一个默认的取景方向的,这个方向如下图所示,坐标原点位于手机横放时的左上角:

fedb4bbfab163f4d72aacac4c4af3c1f.png

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. 图片旋转:由于用户拍照时手机角度不同,所得照片可能需要旋转。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值