Xamarin开发Android笔记:拍照或相册选取图片角度问题

在开发Android应用的时候,可能会遇到类似微信朋友圈中拍照或相册选取图片的场景,拍照或选取图片之后在显示的时候却发现图片的角度不对,明明是竖版拍照,显示出来缺失躺着的。

这是因为在某些特定手机上例如三星系列手机上,预装的相册程序在查看图片的时候会根据拍照的时候手机旋转角度来进行自动旋转。

接下来说明一下具体怎么获取图片的拍摄角度以及如何进行旋转。

 1         /// <summary>
 2         /// 获取指定路径图片拍摄角度
 3         /// </summary>
 4         /// <param name="path"></param>
 5         /// <returns></returns>
 6         protected Int32 GetImageRotate(String path)
 7         {
 8             var angle = 0;
 9             ExifInterface exif = null;
10             try
11             {
12                 exif = new ExifInterface(path);
13             }
14             catch (Exception ex)
15             {
16             }
17 
18             if (exif != null)
19             {
20                 angle = exif.GetAttributeInt(ExifInterface.TagOrientation, -1);
21                 if (angle != -1)
22                 {
23                     switch (angle)
24                     {
25                         case (int)Android.Media.Orientation.Rotate90:
26                             angle = 90;
27                             break;
28                         case (int)Android.Media.Orientation.Rotate180:
29                             angle = 180;
30                             break;
31                         case (int)Android.Media.Orientation.Rotate270:
32                             angle = 270;
33                             break;
34                     }
35                 }
36                 else angle = 0;
37             }
38             return angle;
39         }

获取角度之后,就简单了,接下来对图片进行旋转处理。

                    angle = GetImageRotate(path);

                    if (angle != 0)
                    {
                        var m = new Matrix();
                        var width = bitmap.Width;
                        var height = bitmap.Height;
                        m.SetRotate(angle);
                        bitmap = Bitmap.CreateBitmap(bitmap, 0, 0, width, height, m, true);
                    }

接下来如何处理就看自己的需要了。

posted on 2015-01-14 07:21  宋海鹏  阅读(1868)  评论(0编辑  收藏  举报

导航