斯威夫特:自定义相机保存与图像修改元数据

我正在尝试从图像样本缓冲区中保存一些元数据以及图像。

我需要:

  • 将图像从元数据旋转到方向
  • 从元数据中删除方向
  • 保存到元数据的date
  • 将该图像与元数据一起保存到文档目录中

我试图从数据创build一个UIImage,但是删除了元数据。 我已经尝试从数据中使用CIImage,它保留元数据,但我不能旋转它,然后将其保存到文件。

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) } } 

这是我的代码保存图像。

 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) } 

我最终弄清楚了如何让所有的东西按我需要的方式工作。 帮助我最多的事情是发现一个CFDictionary可以被转换为一个NSMutableDictionary。

这是我最后的代码:

正如你所看到的,我将数字化date的属性添加到EXIF字典中,并更改了方向值。

 private func snapPhoto(success: (UIImage, NSMutableDictionary) -> 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 rawMetadata = CMCopyDictionaryOfAttachments(nil, imageDataSampleBuffer, CMAttachmentMode(kCMAttachmentMode_ShouldPropagate)) let metadata = CFDictionaryCreateMutableCopy(nil, 0, rawMetadata) as NSMutableDictionary let exifData = metadata.valueForKey(kCGImagePropertyExifDictionary as String) as? NSMutableDictionary exifData?.setValue(NSDate().toString("yyyy:MM:dd HH:mm:ss"), forKey: kCGImagePropertyExifDateTimeDigitized as String) metadata.setValue(exifData, forKey: kCGImagePropertyExifDictionary as String) metadata.setValue(1, forKey: kCGImagePropertyOrientation as String) guard let image = UIImage(data: data)?.fixOrientation() else { errorMessage("Couldn't create image") return } success(image, metadata) } } 

而我的最终代码保存与元数据的图像:

许多守卫言论,我讨厌,但它比武力解开更好。

 func saveImage(withMetadata image: UIImage, metadata: NSMutableDictionary) { let filePath = "\(self.documentsPath)/image1.jpg" guard let jpgData = UIImageJPEGRepresentation(image, 1) else { return } // Add metadata to jpgData guard let source = CGImageSourceCreateWithData(jpgData, nil), let uniformTypeIdentifier = CGImageSourceGetType(source) else { return } let finalData = NSMutableData(data: jpgData) guard let destination = CGImageDestinationCreateWithData(finalData, uniformTypeIdentifier, 1, nil) else { return } CGImageDestinationAddImageFromSource(destination, source, 0, metadata) guard CGImageDestinationFinalize(destination) else { return } // Save image that now has metadata self.fileService.save(filePath, data: finalData) } 

这里是我更新的save方法(不是完全一样,当我写这个问题,因为我已经更新到Swift 2.3,但概念是相同的):

 public func save(fileAt path: NSURL, with data: NSData) throws -> Bool { guard let pathString = path.absoluteString else { return false } let directory = (pathString as NSString).stringByDeletingLastPathComponent if !self.fileManager.fileExistsAtPath(directory) { try self.makeDirectory(at: NSURL(string: directory)!) } if self.fileManager.fileExistsAtPath(pathString) { try self.delete(fileAt: path) } return self.fileManager.createFileAtPath(pathString, contents: data, attributes: [NSFileProtectionKey: NSFileProtectionComplete]) } 

我做了上面的代码大大简化的版本。 它确实创build了一个图像文件,但是正如Carlos所说的那样,当你重新加载时,文件中没有自定义的元数据。 根据其他线程,这可能是不可能的。

 func saveImage(_ image: UIImage, withMetadata metadata: NSMutableDictionary, atPath path: URL) -> Bool { guard let jpgData = UIImageJPEGRepresentation(image, 1) else { return false } // make an image source guard let source = CGImageSourceCreateWithData(jpgData as CFData, nil), let uniformTypeIdentifier = CGImageSourceGetType(source) else { return false } // make an image destination pointing to the file we want to write guard let destination = CGImageDestinationCreateWithURL(path as CFURL, uniformTypeIdentifier, 1, nil) else { return false } // add the source image to the destination, along with the metadata CGImageDestinationAddImageFromSource(destination, source, 0, metadata) // and write it out return CGImageDestinationFinalize(destination) }