Swift:自定义相机使用图像保存已修改的元数据

时间:2016-06-30 20:07:44

标签: ios swift swift2

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

我需要:

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

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

2 个答案:

答案 0 :(得分:11)

我最终弄清楚如何让一切按照我需要的方式运作。对我帮助最大的事情是发现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])
}

答案 1 :(得分:0)

我制作了上面代码的大大简化版本。它确实生成了一个图像文件,但正如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)
}