Last active
August 11, 2016 19:37
-
-
Save jjxtra/f515f43922b1264ee44e7fd11d3406a9 to your computer and use it in GitHub Desktop.
Rotating UIImage from AVCaptureSession [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this method rotates the UIImage captured by the capture session manager based on the device orientation when the image was captured ([AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];) | |
- (UIImage*) imageRotated:(UIImage*)image position:(AVCaptureDevicePosition)position orientation:(AVCaptureVideoOrientation)orientation | |
{ | |
CGAffineTransform transform = CGAffineTransformIdentity; | |
CGFloat w = image.size.width * image.scale; | |
CGFloat h = image.size.height * image.scale; | |
CGFloat dw = w; | |
CGFloat dh = h; | |
image = [UIImage imageWithCGImage:image.CGImage scale:1.0f orientation:UIImageOrientationUp]; | |
switch (self.captureLayer.connection.videoOrientation) | |
{ | |
case AVCaptureVideoOrientationPortraitUpsideDown: | |
dw = h; | |
dh = w; | |
transform = CGAffineTransformTranslate(transform, 0.0f, w); | |
transform = CGAffineTransformRotate(transform, -M_PI_2); | |
break; | |
case AVCaptureVideoOrientationLandscapeLeft: | |
if (position == AVCaptureDevicePositionBack) | |
{ | |
transform = CGAffineTransformTranslate(transform, w, h); | |
transform = CGAffineTransformScale(transform, -1.0f, -1.0f); | |
break; | |
} | |
else | |
{ | |
return image; | |
} | |
case AVCaptureVideoOrientationLandscapeRight: | |
if (position == AVCaptureDevicePositionBack) | |
{ | |
return image; | |
} | |
else | |
{ | |
transform = CGAffineTransformTranslate(transform, w, h); | |
transform = CGAffineTransformScale(transform, -1.0f, -1.0f); | |
break; | |
} | |
default: // portrait | |
dw = h; | |
dh = w; | |
transform = CGAffineTransformTranslate(transform, h, 0.0f); | |
transform = CGAffineTransformRotate(transform, M_PI_2); | |
break; | |
} | |
UIGraphicsBeginImageContextWithOptions(CGSizeMake(dw, dh), YES, 1.0f); | |
CGContextConcatCTM(UIGraphicsGetCurrentContext(), transform); | |
[image drawInRect:CGRectMake(0.0f, 0.0f, w, h) blendMode:kCGBlendModeCopy alpha:1.0f]; | |
@autoreleasepool | |
{ | |
image = UIGraphicsGetImageFromCurrentImageContext(); | |
} | |
UIGraphicsEndImageContext(); | |
return image; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Getting the UIImage in the first place: