UIImagePickerController拍照的UIImage竟然旋轉了90度(附解決方案)
問題呈現

正常豎版圖.jpg

問題圖.jpg
獲取返回的UIImage
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; }
分析過程
拍照返回的image 在UIImageView 上顯示,方向沒有問題,儲存到相簿中,也沒有問題。但是將image寫到沙盒目錄下,就會出現上圖的問題,如果把這個圖上傳給伺服器,後臺看到的圖片就不正常。
首先,將image寫到沙盒目錄的時候,對image沒有做任何修改,這一步肯定沒問題。那就是image本身的問題,發現image有個 imageOrientation
的只讀屬性,對應的 UIImageOrientation
是列舉型別,如下:
typedef NS_ENUM(NSInteger, UIImageOrientation) { UIImageOrientationUp,// default orientation UIImageOrientationDown,// 180 deg rotation UIImageOrientationLeft,// 90 deg CCW UIImageOrientationRight,// 90 deg CW UIImageOrientationUpMirrored,// as above but image mirrored along other axis. horizontal flip UIImageOrientationDownMirrored,// horizontal flip UIImageOrientationLeftMirrored,// vertical flip UIImageOrientationRightMirrored, // vertical flip };
列印輸出image.imageOrientation,找出問題
NSLog(@"%ld",(long)image.imageOrientation);
列印輸出 image.imageOrientation
,發現,橫向拍照獲取的 imageOrientation
輸出0,通過列舉來看應該是 UIImageOrientationUp
,但是豎著拍照獲取的 imageOrientation
輸出是3,通過列舉來看應該是 UIImageOrientationRight
,那這應該就是問題所在了。豎著拍照返回來的image的方向預設就是已經逆時針旋轉了90度,我們在往沙盒寫入之前就需要將image調整過來。
解決問題
if(image.imageOrientation!=UIImageOrientationUp){ // Adjust picture Angle UIGraphicsBeginImageContext(image.size); [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)]; image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); }
獲取到image之後通過上邊方法可實現將不正確的 imageOrientation
調整過來。這個坑,找了好久才找出來。至於為什麼UIImageView顯示和儲存在相簿裡沒問題就不清楚了。