小编典典

Swift:自定义相机将修改后的元数据与图像一起保存

swift

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

我需要:

  • 将图像从元数据旋转到方向
  • 从元数据中删除方向
  • 将拍摄日期保存到元数据
  • 将带有元数据的图像保存到文档目录

我尝试从数据创建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)
}

阅读 443

收藏
2020-07-07

共1个答案

小编典典

最后,我弄清楚了如何使所有东西按我需要的方式工作。对我最大的帮助是发现可以将CFDictionary转换为NSMutableDictionary。

这是我的最终代码:

如您所见,我向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])
}
2020-07-07