I am trying to save SOME of the metadata from an image sample buffer along with the image.
I need to:
- Rotate the image to the orientation from the metadata
- Remove orientation from the metadata
- Save the date taken to the metadata
- Save that image with the metadata to the documents directory
I have tried creating a UIImage from the data, but that strips out the metadata. I have tried using a CIImage from the data, which keeps the metadata, but I can't rotate it then save it to a file.
private func snapPhoto(success: (UIImage, CFMutableDictionary) -> Void, errorMessage: String -> Void) {
guard !self.stillImageOutput.capturingStillImage,
let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) else { return }
videoConnection.fixVideoOrientation()
stillImageOutput.captureStillImageAsynchronouslyFromConnection(videoConnection) {
(imageDataSampleBuffer, error) -> Void in
guard imageDataSampleBuffer != nil && error == nil else {
errorMessage("Couldn't snap photo")
return
}
let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
let metadata = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate))
let metadataMutable = CFDictionaryCreateMutableCopy(nil, 0, metadata)
let utcDate = "\(NSDate())"
let cfUTCDate = CFStringCreateCopy(nil, utcDate)
CFDictionarySetValue(metadataMutable!, unsafeAddressOf(kCGImagePropertyGPSDateStamp), unsafeAddressOf(cfUTCDate))
guard let image = UIImage(data: data)?.fixOrientation() else { return }
CFDictionarySetValue(metadataMutable, unsafeAddressOf(kCGImagePropertyOrientation), unsafeAddressOf(1))
success(image, metadataMutable)
}
}
Here is my code for saving the image.
func saveImageAsJpg(image: UIImage, metadata: CFMutableDictionary) {
// Add metadata to image
guard let jpgData = UIImageJPEGRepresentation(image, 1) else { return }
jpgData.writeToFile("\(self.documentsDirectory)/image1.jpg", atomically: true)
}