reading value in CFDictionary with swift

前端 未结 1 603
醉梦人生
醉梦人生 2020-12-28 19:57

I\'m just starting with swift and cocoa. I\'m trying to create a basic app that does image manipulation.

I\'ve allready got all information of the image with this:

相关标签:
1条回答
  • 2020-12-28 20:39

    I've found it much easier to access the properties by 'converting' the CFDictionary to a Swift dictionary.

    let imageSource = CGImageSourceCreateWithURL(imageURL, nil)
    let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary
    let dpiWidth = imageProperties[kCGImagePropertyDPIWidth] as NSNumber
    

    Quick update for Swift 2.0 (excuse all the if lets - I just quickly crafted this code):

    import UIKit
    import ImageIO
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            if let imagePath = NSBundle.mainBundle().pathForResource("test", ofType: "jpg") {
                let imageURL = NSURL(fileURLWithPath: imagePath)
                if let imageSource = CGImageSourceCreateWithURL(imageURL, nil) {
                    if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
                        let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
                        print("the image width is: \(pixelWidth)")
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题