Swift how to modify exif info in images taken from mobile camera

前端 未结 3 766
半阙折子戏
半阙折子戏 2020-12-08 23:47

I use UIImagePickerController to pick images in my iOS App and I know exif info can be got by info[UIImagePickerControllerMediaMetadata]. But when

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-09 00:30

    SWIFT 3

    In case you're capturing a video and getting the CMSampleBuffer there is a way to update the EXIF metadata. In my case in iOS9 I didn't get the DateTimeOriginal, though in iOS10 the DataTimeOriginal was already in. Thus I had to put few additional key-values in.

    self.stillCameraOutput.captureStillImageAsynchronously(from: connectionVideo) { (sampleBuffer, err) in
            if let err = err {
                blockCompletion(nil, err as NSError?)
            }
            else {
                if let sampleBuffer = sampleBuffer {
                    let rawMetadata = CMCopyDictionaryOfAttachments(nil, sampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
                    let metadata = CFDictionaryCreateMutableCopy(nil, 0, rawMetadata) as NSMutableDictionary
    
                    let exifData = metadata.value(forKey: "{Exif}") as? NSMutableDictionary
    
                    print("EXIF DATA: \(exifData)")
    
                    if let dateTime = exifData?["DateTimeOriginal"] as? String {
                        print("DateTime exists \(dateTime)")
                    }
                    else {
                        exifData?.setValue(Date().exifDate(), forKey: "DateTimeOriginal")
                    }
    
                    if let dateTime = exifData?["DateTimeDigitized"] as? String {
                        print("DateTime exists \(dateTime)")
                    }
                    else {
                        exifData?.setValue(Date().exifDate(), forKey: "DateTimeDigitized")
                    }
    
                    metadata.setValue(exifData, forKey: "{Exif}")
    
                    CMSetAttachments(sampleBuffer, metadata as CFDictionary, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
    
                    let rawMetadata2 = CMCopyDictionaryOfAttachments(nil, sampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
                    let metadata2 = CFDictionaryCreateMutableCopy(nil, 0, rawMetadata2) as NSMutableDictionary
    
                    let exifData2 = metadata2.value(forKey: "{Exif}") as? NSMutableDictionary
    
                    print("EXIF DATA: \(exifData2)")
    
                    if let dataImage = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) {
                        blockCompletion(dataImage, nil)
                    }
                    else {
                        blockCompletion(nil, nil)
                    }
                }
                else {
                    blockCompletion(nil, nil)
                }
            }
        }
    

提交回复
热议问题