简体   繁体   中英

How to detect if photo taken from front camera

I want to change orientation of photo taken from front camera vertically with following code:

let reversedImage = UIImage(CGImage: image.CGImage!, scale: 1.0, orientation: .LeftMirrored)

But, how can I detect if photo taken from front camera? I tried following code but it didn't work:

     let availableCameraDevices = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
                for device in availableCameraDevices as! [AVCaptureDevice] {
                    if device.position == .Back {
                        let reversedImage = UIImage(CGImage: image.CGImage!, scale: 1.0, orientation: .LeftMirrored)

                        sp.pickedPhoto = reversedImage

                    }
                    else if device.position == .Front {
                        sp.pickedPhoto = image


                    }
                }

Your code checks for available cameras on the device. What you need to do is read the metadata for the image after you have taken the picture, that will include info on the camera.

Use this solution to read the Exif data that comes with the image to find out which camera obtained it: Exif Data from Image

In Swift, you can do it this way:

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {

    self.dismissViewControllerAnimated(false, completion: { () -> Void in

    })

    if picker.cameraDevice == .Front
    {
        print("Image taken from front camera")
    }
    else if picker.cameraDevice == .Rear
    {
        print("Image taken from back camera")
    }
}

You can check the image EXIF data in the info dictionary UIImagePicker passes in it's callback.

- (IBAction) handleTakePhoto:(UIButton *)sender {

    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;

    [self presentViewController:picker animated:YES completion:nil];

}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    __block NSDictionary* metadata = [info objectForKey:UIImagePickerControllerMediaMetadata];

    dispatch_async(dispatch_get_main_queue(), ^{

        NSLog(@"%@", [metadata valueForKeyPath:@"{Exif}.LensModel"]);

        [picker dismissViewControllerAnimated:YES completion:nil];

    });

}

The above snippet outputs

iPhone 6 Plus back camera 4.15mm f/2.2

You would have to parse out the "front" or "back" parts of the string.

Relying on parsing something that is parsed out of a string raises some red flags -- there is probably a better and more stable way of doing it.

Extract the EXIF data from the image

Facetime Camera:

"{Exif}" =     {
        ColorSpace = 65535;
        PixelXDimension = 3088;
        PixelYDimension = 2320;
    };

Main Camera:

"{Exif}" =     {
        ColorSpace = 65535;
        PixelXDimension = 4032;
        PixelYDimension = 3024;
    };

Use this helper for extracting EXIF data

extension UIImage {

    func getExifData() -> CFDictionary? {
        var exifData: CFDictionary? = nil
        if let data = self.jpegData(compressionQuality: 1.0) {
            data.withUnsafeBytes {
                let bytes = $0.baseAddress?.assumingMemoryBound(to: UInt8.self)
                if let cfData = CFDataCreate(kCFAllocatorDefault, bytes, data.count),
                    let source = CGImageSourceCreateWithData(cfData, nil) {
                    exifData = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
                }
            }
        }
        return exifData
    }
}

Source: https://stackoverflow.com/a/54230367/6576315

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM