在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方法来为已存在的图片设置或修改其本来属性。
下面贴上代码:
- /**
- * 读取图片属性:旋转的角度
- * @param path 图片绝对路径
- * @return degree旋转的角度
- */
- public static int readPictureDegree(String path) {
- int degree = 0;
- try {
- ExifInterface exifInterface = new ExifInterface(path);
- int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,ExifInterface.ORIENTATION_NORMAL);
- 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;
- }
- } catch (IOException e) {
- e.printStackTrace();
- return degree;
- }
- return degree;
- }
能过以上方法得到图片角度后,就可以通过Matrix类对图片进行纠正了,还是贴上完整的代码,如下:
- /**
- * 旋转图片,使图片保持正确的方向。
- * @param bitmap 原始图片
- * @param degrees 原始图片的角度
- * @return Bitmap 旋转后的图片
- */
- public static Bitmap rotateBitmap(Bitmap bitmap, int degrees) {
- if (degrees == 0 || null == bitmap) {
- return bitmap;
- }
- Matrix matrix = new Matrix();
- matrix.setRotate(degrees, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
- Bitmap bmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
- if (null != bitmap) {
- bitmap.recycle();
- }
- return bmp;
- }
通过以上两个步骤,就可以得到一个正着的图片了。当然中间省略了一步:
- Bitmap bmp =BitmapFactory.decodeFile(imageFilePath);