Swift: 讀取相片 Exif

2017041919:05
How to get Exif data from ..
 

讀取專案中的相片Exif  ( IMG_5087.JPG )


import UIKit
import ImageIO

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let url = Bundle.main.url(forResource:"IMG_5087", withExtension: "JPG")!
        let src = CGImageSourceCreateWithURL(url as CFURL, nil)!
        let result = CGImageSourceCopyPropertiesAtIndex(src, 0, nil)! as NSDictionary
        print(result)
        // just proving it really is a dictionary
   
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}


 


結果

{
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 1;
    PixelHeight = 3264;
    PixelWidth = 2448;
    ProfileName = "sRGB IEC61966-2.1";
    "{Exif}" =     {
        ApertureValue = "2.526069127123609";
        BrightnessValue = "8.864634146341464";
        ColorSpace = 1;
        ComponentsConfiguration =         (
            1,
            2,
            3,
            0
        );
        DateTimeDigitized = "2013:05:25 16:42:51";
        DateTimeOriginal = "2013:05:25 16:42:51";
        ExifVersion =         (
            2,
            2,
            1
        );
        ExposureMode = 0;
        ExposureProgram = 2;
        FNumber = "2.4";
        Flash = 16;
        FlashPixVersion =         (
            1,
            0
        );
        FocalLenIn35mmFilm = 33;
        FocalLength = "4.13";
        ISOSpeedRatings =         (
            50
        );
        MeteringMode = 5;
        PixelXDimension = 2448;
        PixelYDimension = 3264;
        SceneCaptureType = 0;
        SensingMethod = 2;
        ShutterSpeedValue = "9.556529360210341";
        SubjectArea =         (
            1631,
            1223,
            881,
            881
        );
        WhiteBalance = 0;
    };
    "{GPS}" =     {
        Latitude = "24.03216666666667";
        LatitudeRef = N;
        Longitude = "121.629";
        LongitudeRef = E;
    };
    "{TIFF}" =     {
        DateTime = "2013:05:25 16:42:51";
        Make = Apple;
        Model = "iPhone 5";
        Orientation = 1;
        ResolutionUnit = 2;
        XResolution = 72;
        YResolution = 72;
    };
}


讀取網路上某張圖片Exif

 

        let fileURL = NSURL(string: "http://xxx.com/IMG_5087.JPG")

        if let imageSource = CGImageSourceCreateWithURL(fileURL!, nil) {
            let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
            if let dict = imageProperties as? [String: Any] {
                print(dict)
            }
        }


結果

["PixelHeight": 3264, "DPIHeight": 72, "{Exif}": {
    ApertureValue = "2.526069127123609";
    BrightnessValue = "8.864634146341464";
    ColorSpace = 1;
    ComponentsConfiguration =     (
        1,
        2,
        3,
        0
    );
    DateTimeDigitized = "2013:05:25 16:42:51";
    DateTimeOriginal = "2013:05:25 16:42:51";
    ExifVersion =     (
        2,
        2,
        1
    );
    ExposureMode = 0;
    ExposureProgram = 2;
    FNumber = "2.4";
    Flash = 16;
    FlashPixVersion =     (
        1,
        0
    );
    FocalLenIn35mmFilm = 33;
    FocalLength = "4.13";
    ISOSpeedRatings =     (
        50
    );
    MeteringMode = 5;
    PixelXDimension = 2448;
    PixelYDimension = 3264;
    SceneCaptureType = 0;
    SensingMethod = 2;
    ShutterSpeedValue = "9.556529360210341";
    SubjectArea =     (
        1631,
        1223,
        881,
        881
    );
    WhiteBalance = 0;
}, "DPIWidth": 72, "Depth": 8, "ProfileName": sRGB IEC61966-2.1, "Orientation": 1, "{TIFF}": {
    DateTime = "2013:05:25 16:42:51";
    Make = Apple;
    Model = "iPhone 5";
    Orientation = 1;
    ResolutionUnit = 2;
    XResolution = 72;
    YResolution = 72;
}, "ColorModel": RGB, "{GPS}": {
    Latitude = "24.03216666666667";
    LatitudeRef = N;
    Longitude = "121.629";
    LongitudeRef = E;
}, "PixelWidth": 2448]


讀取相簿某張圖片Exif

 

     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

//方法 #1
        if let urlAny = info[UIImagePickerControllerReferenceURL]
        {
            let url = urlAny as! URL
            
            let fetchOptions = PHFetchOptions()
            fetchOptions.fetchLimit = 1
            fetchOptions.includeAssetSourceTypes = .typeUserLibrary
            
            let imgMgr = PHImageManager.default()
            
            let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [url], options: fetchOptions)
            fetchResult.enumerateObjects({ (asset, count, stop) in
                let finalRequestOptions = PHImageRequestOptions()
                imgMgr.requestImage(for: asset, targetSize: PHImageManagerMaximumSize,
                                    contentMode: .aspectFit, options: finalRequestOptions,
                                    resultHandler: { (image, map) in
                                        
                            if let imagePathOpt = map?["PHImageFileURLKey"] {

                                let imagePath = imagePathOpt as! CFURL
                                print("str url: \(imagePath)")
                                            
                                let myOptions = CFDictionaryCreate(nil, nil, nil, 0, nil, nil)
                                            
                                // this next part fails
                                if let imageSource = CGImageSourceCreateWithURL(imagePath, myOptions) {
                                        let props = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil)
                                            print("props: \(String(describing: props))")
                                        }
                            }
                                        
                })
            })
        

        }
    
        
/*
方法  #2
 
 http://titirobo-develop.hatenablog.jp/entry/2016/10/20/143111
 
         
         let assetUrl:NSURL = (info[UIImagePickerControllerReferenceURL] as! NSURL?)!
         let url = NSURL(string: (assetUrl.description))!
         
         let result = PHAsset.fetchAssets(withALAssetURLs: [url as URL], options: nil)
         
         let asset:PHAsset = result.firstObject! as PHAsset
         let editOptions = PHContentEditingInputRequestOptions()
         editOptions.isNetworkAccessAllowed = true
         
         asset.requestContentEditingInput(with: editOptions, completionHandler: { (contentEditingInput, _) -> Void in
         let url = contentEditingInput?.fullSizeImageURL
         let inputImage:CIImage = CoreImage.CIImage(contentsOf: url!)!
         
         //let meta = inputImage.properties as NSDictionary?
         //let exif:NSDictionary = meta!["{Exif}"] as! NSDictionary
         
         print(inputImage.properties)
         
         
         })
         

 */
        dismiss(animated: true, completion: nil)

    }

結果

str url: file:///Users/fire/Library/Developer/CoreSimulator/Devices/DEA1BA01-6533-45B7-9AA3-7E0EC3800E05/data/Media/DCIM/100APPLE/IMG_0007.JPG
props: Optional({
    ColorModel = RGB;
    DPIHeight = 72;
    DPIWidth = 72;
    Depth = 8;
    Orientation = 1;
    PixelHeight = 3264;
    PixelWidth = 2448;
    ProfileName = "sRGB IEC61966-2.1";
    "{Exif}" =     {
        ApertureValue = "2.526069127123609";
        BrightnessValue = "6.127303182579564";
        ColorSpace = 1;
        ComponentsConfiguration =         (
            1,
            2,
            3,
            0
        );
        DateTimeDigitized = "2013:04:26 15:40:35";
        DateTimeOriginal = "2013:04:26 15:40:35";
        ExifVersion =         (
            2,
            2,
            1
        );
        ExposureMode = 0;
        ExposureProgram = 2;
        FNumber = "2.4";
        Flash = 16;
        FlashPixVersion =         (
            1,
            0
        );
        FocalLenIn35mmFilm = 33;
        FocalLength = "4.13";
        ISOSpeedRatings =         (
            50
        );
        MeteringMode = 3;
        PixelXDimension = 2448;
        PixelYDimension = 3264;
        SceneCaptureType = 0;
        SensingMethod = 2;
        ShutterSpeedValue = "7.570722057368942";
        SubjectArea =         (
            2694,
            1417,
            610,
            612
        );
        WhiteBalance = 0;
    };
    "{GPS}" =     {
        Altitude = "59.33380480905233";
        AltitudeRef = 0;
        Latitude = "25.039";
        LatitudeRef = N;
        Longitude = "121.5678333333333";
        LongitudeRef = E;
    };
    "{JFIF}" =     {
        DensityUnit = 1;
        JFIFVersion =         (
            1,
            0,
            2
        );
        XDensity = 72;
        YDensity = 72;
    };
    "{TIFF}" =     {
        DateTime = "2014:02:19 22:44:54";
        Make = Apple;
        Model = "iPhone 5";
        Orientation = 1;
        ResolutionUnit = 2;
        Software = "Adobe Photoshop CS3 Windows";
        XResolution = 72;
        YResolution = 72;
    };
})

 



以上相關的程式 ( 6.7MB)
https://www.dropbox.com/s/feurv0jsa77xvk7/swift_exif_demo.zip?dl=0