如何在Swift 4中从UIImage读取exif数据?

Din*_* Kc 4 core-image uiimage ios swift

我有一幅带有大量exif信息的图像。但是,当尝试快速读取exif信息时,它显示的exif信息数量有限。

我尝试了以下代码:

let data = UIImageJPEGRepresentation(image, 1.0)
let source = CGImageSourceCreateWithData(data! as CFData, nil)
let metadata = (CGImageSourceCopyPropertiesAtIndex(source!, 0, nil))
debugPrint(metadata ?? "nil")
Run Code Online (Sandbox Code Playgroud)

并显示以下结果:

    {
    ColorModel = RGB;
    Depth = 8;
    Orientation = 6;
    PixelHeight = 2448;
    PixelWidth = 3264;
    ProfileName = "sRGB IEC61966-2.1";
    "{Exif}" =     {
        ColorSpace = 1;
        PixelXDimension = 3264;
        PixelYDimension = 2448;
    };
    "{JFIF}" =     {
        DensityUnit = 0;
        JFIFVersion =         (
            1,
            0,
            1
        );
        XDensity = 72;
        YDensity = 72;
    };
    "{TIFF}" =     {
        Orientation = 6;
    };
}
Run Code Online (Sandbox Code Playgroud)

如何从UIImage中读取所有exif信息?

Bha*_*Dev 5

如果您的图像是使用avcapturesession.than捕获的,则以下是提取exif数据的代码。

photoFileOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(sampleBuffer, error) in
                if (sampleBuffer != nil) {
                        let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer!)
                        let image = self.processPhoto(imageData!)
                        let source: CGImageSource = CGImageSourceCreateWithData((imageData as! CFMutableData), nil)!

                        let metadata = CGImageSourceCopyPropertiesAtIndex(source, 0,nil) as! [String:Any]

                        print("exif data = \(metadata![kCGImagePropertyExifDictionary as String] as? [String : AnyObject]) ")

                        completionHandler(true)
                    } else {
                        completionHandler(false)
                    }
                }
Run Code Online (Sandbox Code Playgroud)


Chr*_*zak 5

我怀疑UIImageJPEGRepresentation函数是罪魁祸首,因为它执行从 HEIC 到 JPEG 的转换(假设您从照片应用程序中提取图像)。许多有价值的 Exif 标签,包括地理位置等信息,似乎在转换过程中丢失了。