IOS 拍照旋转修正

  1. - (UIImage *)fixOrientation:(UIImage *)aImage {
  2. // No-op if the orientation is already correct
  3. if (aImage.imageOrientation == UIImageOrientationUp)
  4. return aImage;
  5. // We need to calculate the proper transformation to make the image upright.
  6. // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
  7. CGAffineTransform transform = CGAffineTransformIdentity;
  8. switch (aImage.imageOrientation) {
  9. case UIImageOrientationDown:
  10. case UIImageOrientationDownMirrored:
  11. transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
  12. transform = CGAffineTransformRotate(transform, M_PI);
  13. break;
  14. case UIImageOrientationLeft:
  15. case UIImageOrientationLeftMirrored:
  16. transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
  17. transform = CGAffineTransformRotate(transform, M_PI_2);
  18. break;
  19. case UIImageOrientationRight:
  20. case UIImageOrientationRightMirrored:
  21. transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
  22. transform = CGAffineTransformRotate(transform, -M_PI_2);
  23. break;
  24. default:
  25. break;
  26. }
  27. switch (aImage.imageOrientation) {
  28. case UIImageOrientationUpMirrored:
  29. case UIImageOrientationDownMirrored:
  30. transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
  31. transform = CGAffineTransformScale(transform, -1, 1);
  32. break;
  33. case UIImageOrientationLeftMirrored:
  34. case UIImageOrientationRightMirrored:
  35. transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
  36. transform = CGAffineTransformScale(transform, -1, 1);
  37. break;
  38. default:
  39. break;
  40. }
  41. // Now we draw the underlying CGImage into a new context, applying the transform
  42. // calculated above.
  43. CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
  44. CGImageGetBitsPerComponent(aImage.CGImage), 0,
  45. CGImageGetColorSpace(aImage.CGImage),
  46. CGImageGetBitmapInfo(aImage.CGImage));
  47. CGContextConcatCTM(ctx, transform);
  48. switch (aImage.imageOrientation) {
  49. case UIImageOrientationLeft:
  50. case UIImageOrientationLeftMirrored:
  51. case UIImageOrientationRight:
  52. case UIImageOrientationRightMirrored:
  53. // Grr...
  54. CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
  55. break;
  56. default:
  57. CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
  58. break;
  59. }
  60. // And now we just create a new UIImage from the drawing context
  61. CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
  62. UIImage *img = [UIImage imageWithCGImage:cgimg];
  63. CGContextRelease(ctx);
  64. CGImageRelease(cgimg);
  65. return img;
  66. }
上一篇:C#之内存分配


下一篇:Spark调研笔记第3篇 - Spark集群相应用的调度策略简单介绍