iOS:如何从磁盘上的照片文件中提取缩略图和元数据

Pap*_*lon 5 metadata photo thumbnails avfoundation ios

Apple 文档https://developer.apple.com/documentation/avfoundation/cameras_and_media_capture/capturing_still_and_live_photos/capturing_thumbnail_and_preview_images解释了如何捕获缩略图。

\n

在底部,它说

\n
\n

如果您请求嵌入缩略图图像,则该图像无法从 AVCapturePhoto 对象\xe2\x80\x94 直接访问,它嵌入\n通过调用照片对象的\nfileDataRepresentation 获取的图像文件数据中() 方法。

\n
\n

似乎不可能将嵌入的缩略图与主照片分开。那么嵌入缩略图是什么意思呢?

\n

我想将 JPG 和原始 DNG 格式的 AVCapturePhoto(两者都请求嵌入缩略图)保存到 App\Documents目录(我不使用 PhotoKit),然后将其加载回UIImageView.

\n

我保存了这样的照片:

\n
if let data = capturePhoto.fileDataRepresentation() {\n    data.write(to: documentsPath, options: [])\n}\n
Run Code Online (Sandbox Code Playgroud)\n

并将其加载回如下所示UIImage

\n
if let data = FileManager.default.contents(at: path) {\n    let image = UIImage(data: data)\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但最好先加载嵌入的thubmail。如果用户单击查看大图像,则加载完整图像文件。

\n

我还想显示元数据,例如 GPS 位置、闪光灯状态、ISO、快门速度等。我不知道该怎么做。

\n

Rhy*_*man 4

AVFoundation包装了AVAsset一些元数据类型,但显然不是 EXIF 数据。如果你想要缩略图,你必须使用CoreGraphics框架。此函数获取缩略图(如果存在),将最大边长限制为 512 像素。

public func getImageThumbnail(url: URL) -> CGImage? {
    guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
    
    let thumbnailOptions: [String: Any] = [
        kCGImageSourceCreateThumbnailWithTransform as String: true,
        kCGImageSourceCreateThumbnailFromImageIfAbsent as String: false, // true will create if thumbnail not present
        kCGImageSourceThumbnailMaxPixelSize as String: 512
    ]
    return CGImageSourceCreateThumbnailAtIndex(imageSource, 0, thumbnailOptions as CFDictionary);
}
Run Code Online (Sandbox Code Playgroud)

对于所有其余元数据,您可以使用CGImageSourceCopyPropertiesAtIndexCGImageSourceCopyMetadataAtIndex