当前位置: 移动技术网 > 移动技术>移动开发>Android > Android通过ExifInterface判断Camera图片方向的方法

Android通过ExifInterface判断Camera图片方向的方法

2019年07月31日  | 移动技术网移动技术  | 我要评论

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

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

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

总结

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网