【问题标题】:Image captured from custom camera gets rotated after cropping iOS从自定义相机捕获的图像在裁剪 iOS 后被旋转
【发布时间】:2017-04-15 17:08:44
【问题描述】:

我在裁剪图像后面临图像旋转问题。我已经将我目前使用的逐步方法放在下面。

这是我得到结果的过程:

步骤:1 通过自定义相机拍照

- (void)captureImageWithCompletionHander:(void (^)(id))completionHandler{
    [_cameraOverlayView hideHightLightOverlay];
    if (_isCapturing) return;

    __weak typeof(self) weakSelf = self;
    [weakSelf hideGLKView:YES completion:^{
        [weakSelf hideGLKView:NO completion:^{
            [weakSelf hideGLKView:YES completion:nil];
        }];
    }];
    _isCapturing = YES;

    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in self.stillImageOutput.connections){
        for (AVCaptureInputPort *port in [connection inputPorts]){
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ){
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) break;
    }

    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler: ^(CMSampleBufferRef imageSampleBuffer, NSError *error){
        if(!CMSampleBufferIsValid(imageSampleBuffer)){
            return;
        }
        NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];

        UIImage * capturedImage = [[UIImage alloc]initWithData:imageData scale:1];
        NSLog(@"%lu",(unsigned long)UIImageJPEGRepresentation(capturedImage, 1.0).length);
        if (_myDevice == [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo][0]) {
            capturedImage = capturedImage;
        }else if (_myDevice == [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo][1]) {
        }

        [weakSelf hideGLKView:NO completion:nil];
        completionHandler(capturedImage);
         _isCapturing = NO;
     }];
}

步骤:2固定方向

-(id)initWithImage:(UIImage*) image{
    self =  [super init];
    if (self){
        self.originalImage = [image fixOrientation];
    }

    return self;
}

//Method for fix orientation
@implementation UIImage (fixOrientation)

- (UIImage *)fixOrientation {

    // No-op if the orientation is already correct
    if (self.imageOrientation == UIImageOrientationUp) return self;

    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;

    switch (self.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;

        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;

        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, self.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationUpMirrored:
            break;
    }

    switch (self.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;

        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, self.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationUp:
        case UIImageOrientationDown:
        case UIImageOrientationLeft:
        case UIImageOrientationRight:
            break;
    }

    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
                                             CGImageGetBitsPerComponent(self.CGImage), 0,
                                             CGImageGetColorSpace(self.CGImage),
                                             CGImageGetBitmapInfo(self.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (self.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
            break;

        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
            break;
    }

    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}
@end

步骤:3裁剪图像

-(UIImage *)cropImage:(UIImage *)image{
    CGFloat overlayHeight = self.frame.size.height;
    UIImageOrientation originalOrientation = image.imageOrientation;
    CGFloat originalScale = image.scale;
    CIImage *rawImage = [CIImage imageWithCGImage:image.CGImage];

    NSMutableDictionary *rectangleCoordinates = [NSMutableDictionary new];
    rectangleCoordinates[@"inputTopLeft"] = [CIVector vectorWithCGPoint:CGPointMake(topLeftPath.x * _absoluteWidth, (overlayHeight - topLeftPath.y) * _absoluteHeight)];
    rectangleCoordinates[@"inputTopRight"] = [CIVector vectorWithCGPoint:CGPointMake(topRightPath.x * _absoluteWidth, (overlayHeight - topRightPath.y) * _absoluteHeight)];
    rectangleCoordinates[@"inputBottomLeft"] = [CIVector vectorWithCGPoint:CGPointMake(bottomLeftPath.x * _absoluteWidth, (overlayHeight - bottomLeftPath.y) * _absoluteHeight)];
    rectangleCoordinates[@"inputBottomRight"] = [CIVector vectorWithCGPoint:CGPointMake(bottomRightPath.x * _absoluteWidth, (overlayHeight - bottomRightPath.y) * _absoluteHeight)];
    rawImage = [rawImage imageByApplyingFilter:@"CIPerspectiveCorrection" withInputParameters:rectangleCoordinates];

    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef cgImage = [context createCGImage:rawImage fromRect:[rawImage extent]];
    UIImage *RImage = [UIImage imageWithCGImage:cgImage scale:originalScale orientation:originalOrientation];
    return RImage;
}

结果:

  • 捕获图像后,我正在显示原始图像并且看起来很直。没有问题。

查看图片:

  • 但裁剪后会旋转

查看图片:

一些我已经尝试过但没有奏效的参考资料:

Using CoreImage to filter an image results in image rotation

iOS UIImagePickerController result image orientation after upload

iOS - UIImageView - how to handle UIImage image orientation

How to get the Correct orientation of the image selected from the Default Image gallery

Convert a UIImage to a CIImage to crop to a CGRect. AVFoundation

如果有人指导解决这个问题,那就太好了。

提前致谢。

【问题讨论】:

  • 试试这个进行裁剪.. - (UIImage )crop:(CGRect)rect { rect = CGRectMake(rect.origin.xself.scale, rect.origin.y self.scale, rect.size.widthself.scale, rect.size.height*self.scale); CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect); UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scaleorientation:self.imageOrientation]; CGImageRelease(imageRef);返回结果; }
  • 我认为你应该参考这个答案来裁剪图像我在我的项目中使用这个答案并解决我的问题..stackoverflow.com/questions/158914/cropping-an-uiimage

标签: ios objective-c iphone core-image ciimage


【解决方案1】:

只需在“cropImage”方法的下一行中将方向替换为 UIImageOrientationUp。

UIImage *RImage = [UIImage imageWithCGImage:cgImage scale:originalScale orientation:UIImageOrientationUp];

【讨论】:

    【解决方案2】:

    经过这么多实验和尝试这么多解决方案,最后我通过转移到UIBeizerPath解决了这个问题。

    我注意到方向问题的出现只是因为CIImage,它永远不会得到解决。即使是原始图像也能正确显示,因为CIImage 在裁剪后会旋转。

    所以尝试使用UIBeizerPath & 这是我所做的:

    UIBezierPath *path = [_overlayView getPath];
    CGRect rect = CGRectZero;
    rect.size = _detectedImage.frame.size;
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.frame = CGRectMake(0, 0, _detectedImage.frame.size.width, _detectedImage.frame.size.height);
    shapeLayer.path = path.CGPath;
    shapeLayer.fillColor = [[UIColor whiteColor] CGColor];
    shapeLayer.backgroundColor = [[UIColor clearColor] CGColor];
    [_detectedImage.layer setMask:shapeLayer];
    
    UIGraphicsBeginImageContextWithOptions(_detectedImage.layer.frame.size, NO, 0);
    [_detectedImage.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIImage *cpImage = [outputImage imageByTrimmingTransparentPixelsRequiringFullOpacity:YES];
    UIGraphicsEndImageContext();
    

    希望对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-11-05
      • 2013-05-26
      • 1970-01-01
      • 2020-02-11
      • 1970-01-01
      • 2013-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多