I am trying to crop a video frame. I have recorded the video using AVFoundation
framework. I need to crop the snapped image and recorded video into a square shape. I have done it for the UIImage
which worked, and now I am trying to crop the video.
- (UIImage *)squareImageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize { // Cropping UIImage is working fine. CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0,0, image.size.width, image.size.width)); UIImage *result = [UIImage imageWithCGImage:imageRef scale:image.scale orientation:image.imageOrientation]; CGImageRelease(imageRef); return result; }
I tried to crop the video but it resulted in changing the whole video frame without cropping, and it looks stretched.
_writer = [AVAssetWriter assetWriterWithURL:url fileType:AVFileTypeQuickTimeMovie error:nil]; NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoCodecH264, AVVideoCodecKey, [NSNumber numberWithInt: 320], AVVideoWidthKey, [NSNumber numberWithInt: 320], AVVideoHeightKey, nil]; _videoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings]; [_writer addInput:_videoInput];
Can anybody help me to solve this cropping issue for video? Thanks in advance.
Below is my code which is used to crop video.we need to set AVVideoCompressionPropertiesKey
which contains AVVideoCleanApertureKey
key for video settings.
I Reffered : How to crop video into square iOS with AVAssetWriter
NSDictionary *videoCleanApertureSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:cx], AVVideoCleanApertureWidthKey, [NSNumber numberWithInt:cx], AVVideoCleanApertureHeightKey, [NSNumber numberWithInt:10], AVVideoCleanApertureHorizontalOffsetKey, [NSNumber numberWithInt:10], AVVideoCleanApertureVerticalOffsetKey, nil]; NSDictionary *videoAspectRatioSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:3], AVVideoPixelAspectRatioHorizontalSpacingKey, [NSNumber numberWithInt:3],AVVideoPixelAspectRatioVerticalSpacingKey, nil]; NSDictionary *codecSettings = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInt:960000], AVVideoAverageBitRateKey, [NSNumber numberWithInt:1],AVVideoMaxKeyFrameIntervalKey, videoCleanApertureSettings, AVVideoCleanApertureKey, //videoAspectRatioSettings, AVVideoPixelAspectRatioKey, //AVVideoProfileLevelH264Main30, AVVideoProfileLevelKey, nil]; NSString *targetDevice = [[UIDevice currentDevice] model]; NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys: AVVideoScalingModeResizeAspectFill,AVVideoScalingModeKey, AVVideoCodecH264, AVVideoCodecKey, codecSettings,AVVideoCompressionPropertiesKey, [NSNumber numberWithInt:cx], AVVideoWidthKey, [NSNumber numberWithInt:cx], AVVideoHeightKey, nil]; _videoInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:videoSettings];