项目中需要用UIImagePickerController拍摄照片,然后减小大小,并裁减中间的部分。
发现:UIImagePickerController 拍摄得到的UIImage , 方向可能会旋转90度。
在网上搜了各种方法,没有解决。 最终通过各种试验解决了我的问题,代码如下:
// imageToHandle是通过UIImagePickerController得到的照片
CGFloat scale = imageToHandle.scale;
//裁减区域的大小,(drawWidth,drawHeight)是照片缩小后的大小
CGSize cropSize = CGSizeMake(drawWidth, drawWidth * 6 / 9);
CGFloat top = drawHeight / 2 - cropSize.height / 2;
CGFloat middle = cropSize.height;
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
CGContextRef context = CGBitmapContextCreate(NULL, cropSize.width * scale, cropSize.height * scale, 8, 0, colorspace, kCGImageAlphaNone);
CGContextRotateCTM(context, -M_PI_2);
CGContextTranslateCTM(context, -top-middle, 0);
CGContextDrawImage(context, CGRectMake(0,0, drawHeight, drawWidth), imageToHandle.CGImage);
CGImageRef image = CGBitmapContextCreateImage(context);
CGColorSpaceRelease(colorspace);
CGContextRelease(context);
// self.cropedImage为最终得到的照片
self.cropedImage = [UIImage imageWithCGImage:image];
===
拍摄时屏幕的照片区域是这样的:
1-------2
| |
| |
| |
| |
| |
| |
3-------4
但是底层数据的存储是这样的(无论imageOrientation是什么)
1------------------3
| |
| |
2------------------ 4
所以通过CGBitmapContext处理,需要旋转,移动坐标系,以得到正确的方向。
UIImagePickerController 拍摄的照片 方向
原文:http://www.cnblogs.com/beddup/p/4945038.html