UIImagePickerController 拍摄的照片 方向

项目中需要用UIImagePickerController拍摄照片,然后缩小,并裁减。发现UIImagePickerController拍摄得到的UIImage , 方向可能会旋转90度。

也在网上搜了一些方法,不太理想,最终使用以下代码解决了我的问题:移动,旋转CGBitmapContext,然后重画UIImage

 1     //  imageToHandle是通过UIImagePickerController得到的照片
 2 
 3             CGFloat scale = imageToHandle.scale; 
 4 
 5  
 6 
 7             //裁减区域的大小,drawWidth是照片缩小后的宽度
 8 
 9             CGSize cropSize = CGSizeMake(drawWidth, drawWidth * 6 / 9);
10 
11             CGFloat top = drawHeight / 2 - cropSize.height / 2;
12 
13             CGFloat middle = cropSize.height;
14 
15            CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
16 
17             CGContextRef context = CGBitmapContextCreate(NULL, cropSize.width * scale, cropSize.height * scale, 8, 0, colorspace, kCGImageAlphaNone);
18 
19             CGContextRotateCTM(context, -M_PI_2);
20 
21             CGContextTranslateCTM(context, -top-middle, 0);
22 
23             CGContextDrawImage(context, CGRectMake(0,0, drawHeight, drawWidth), imageToHandle.CGImage);
24 
25              CGImageRef image = CGBitmapContextCreateImage(context); 
26 
27             CGColorSpaceRelease(colorspace);
28 
29             CGContextRelease(context);
30 
31     // self.cropedImage为最终得到的照片  
32 
33              self.cropedImage = [UIImage imageWithCGImage:image];
34 
35  

===

拍摄时屏幕的照片区域是这样的:

1-------2

|                     |

|                     |

|                     |

|                     |

|                     |

|                     |

3-------4

但是底层数据的存储是这样的

1------------------3

|                                                    |

|                                                    |

2------------------ 4

所以通过CGBitmapContext处理,旋转,移动contextRef,以得到正确的方向。

原文地址:https://www.cnblogs.com/beddup/p/4945038.html