设为首页 加入收藏

TOP

Android判断相机图片朝向
2015-08-31 21:25:19 来源: 作者: 【 】 浏览:28
Tags:Android 判断 相机 图片 朝向

代码如下:


?/**
? *
? * 利用给定路径下的图片设置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) {
? ?}
? }
?}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java同步机制中用到的锁的思想 下一篇史上最复杂的验证邮件地址的正则..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: