Android 根据角度旋转图片,当时是为了适配 三星手机

来源:互联网 发布:穿西装要注意什么知乎 编辑:程序博客网 时间:2024/04/30 15:39

在Android开发过程中,几乎每个应用都会或多或少的涉及到对图片的处理。经常遇到的一个情况就是,取得的图片是横着的,而实际需要的图片是正着的,也就是竖着的。这里就涉及到对图片横坚情况的判断,也就是图片的当前的角度。然后根据角度来纠正,得到想要的图片。

       在Android的源代码里提供了一个专门读写图片信息的类ExifInterface,官方给出的注释为:This is a class for reading and writing Exif tags in a JPEG file ,可见ExifInterface是专门用来读写JPEG图片文件Exif信息的类。

        Exif信息里面就包括了角度,GPS经纬度,白平衡,闪光灯等信息。ExifInterface的用法相对简单,只有一个带参的构造方法,将图片文件地址传过去就可以了。类里提供了getAttribute方法来取得各种属性,当得也可以用setAttribute方法来为已存在的图片设置或修改其本来属性。

       下面贴上代码:

  1. /** 
  2.  * 读取图片属性:旋转的角度 
  3.  * @param path 图片绝对路径 
  4.  * @return degree旋转的角度 
  5.  */  
  6. public static int readPictureDegree(String path) {  
  7.     int degree = 0;  
  8.     try {  
  9.         ExifInterface exifInterface = new ExifInterface(path);  
  10.         int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);  
  11.         switch (orientation) {  
  12.         case ExifInterface.ORIENTATION_ROTATE_90:  
  13.             degree = 90;  
  14.             break;  
  15.         case ExifInterface.ORIENTATION_ROTATE_180:  
  16.             degree = 180;  
  17.             break;  
  18.         case ExifInterface.ORIENTATION_ROTATE_270:  
  19.             degree = 270;  
  20.             break;  
  21.         }  
  22.     } catch (IOException e) {  
  23.         e.printStackTrace();  
  24.         return degree;  
  25.     }  
  26.     return degree;  

得到bitmap:

  1. Bitmap bmp =BitmapFactory.decodeFile(imageFilePath);  


  1. /** 
  2.  * 旋转图片,使图片保持正确的方向。 
  3.  * @param bitmap 原始图片 
  4.  * @param degrees 原始图片的角度 
  5.  * @return Bitmap 旋转后的图片 
  6.  */  
  7. public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {  
  8.     if (degrees == 0 || null == bitmap) {  
  9.         return bitmap;  
  10.     }  
  11.     Matrix matrix = new Matrix();  
  12.     matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);  
  13.     Bitmap bmp = Bitmap.createBitmap(bitmap, 00, bitmap.getWidth(), bitmap.getHeight(), matrix, true);  
  14.     if (null != bitmap) {  
  15.         bitmap.recycle();  
  16.     }  
  17.     return bmp;  
  18. }
最终得到 矫正后的bitmap

0 0
原创粉丝点击