IOS: How can a custom camera keep images always in the correct orientation?

I am currently implementing a custom camera with IOS. I want the camera to keep the images in the album always in the right direction, just like the official iOS camera: no matter what orientation you hold the camera in, you can always see the photo that will keep the correct orientation. I checked a lot of source code, they seem to save the image quite randomly with the following:

var image  = UIImage(cgImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.right)

      

But this only works when the device is upright. Can anyone provide any suggestions?

I also tried to get orientation

let uiorientation = UIApplication.shared.statusBarOrientation

      

But it always returns portrait when portrait is locked on screen.

+3


source to share


1 answer


You need to update the rotation of the image when you receive the object UIImage

. Pass the image produced by the image picker to this method.

Swift

func getNormalizedImage(rawImage: UIImage) -> UIImage {

    if (rawImage.imageOrientation == .up) {
        return rawImage
    }

    UIGraphicsBeginImageContextWithOptions(rawImage.size, false, rawImage.scale)
    rawImage.draw(in: CGRect(x:0, y:0, width:rawImage.size.width, height:rawImage.size.height))

    let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return normalizedImage!
}

      



Objective-C

+(UIImage *)getNormalizedImage:(UIImage *)rawImage {

    if(rawImage.imageOrientation == UIImageOrientationUp)
    return rawImage;

    UIGraphicsBeginImageContextWithOptions(rawImage.size, NO, rawImage.scale);
    [rawImage drawInRect:(CGRect){0, 0, rawImage.size}];
    UIImage *normalizedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return normalizedImage;
}

      

+3


source







All Articles