Skip to content

Instantly share code, notes, and snippets.

@jjxtra
Last active August 11, 2016 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjxtra/f515f43922b1264ee44e7fd11d3406a9 to your computer and use it in GitHub Desktop.
Save jjxtra/f515f43922b1264ee44e7fd11d3406a9 to your computer and use it in GitHub Desktop.
Rotating UIImage from AVCaptureSession [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:]
// 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;
}
@jjxtra
Copy link
Author

jjxtra commented Aug 11, 2016

Getting the UIImage in the first place:

NSData* imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage* image = [UIImage imageWithData:imageData];

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment