【问题标题】:reading value in CFDictionary with swift快速读取 CFDictionary 中的值
【发布时间】:2016-12-02 23:52:22
【问题描述】:

我只是从 swift 和 cocoa 开始。我正在尝试创建一个进行图像处理的基本应用程序。

我已经有了这张图片的所有信息:

let imageRef:CGImageSourceRef = CGImageSourceCreateWithURL(url, nil).takeUnretainedValue()
let imageDict:CFDictionaryRef = CGImageSourceCopyPropertiesAtIndex(imageRef, 0, nil).takeUnretainedValue()

字典包含以下信息:

{
    ColorModel = Gray;
    DPIHeight = 300;
    DPIWidth = 300;
    Depth = 1;
    Orientation = 1;
    PixelHeight = 4167;
    PixelWidth = 4167;
    "{Exif}" =     {
        ColorSpace = 65535;
        DateTimeDigitized = "2014:07:09 20:25:49";
        PixelXDimension = 4167;
        PixelYDimension = 4167;
    };
    "{TIFF}" =     {
        Compression = 1;
        DateTime = "2014:07:09 20:25:49";
        Orientation = 1;
        PhotometricInterpretation = 0;
        ResolutionUnit = 2;
        Software = "Adobe Photoshop CS6 (Macintosh)";
        XResolution = 300;
        YResolution = 300;
    };
}

现在我想使用以下代码读取 DPI 的值,但“__conversion”存在一些问题,我不明白。

let dpiH:NSNumber = CFDictionaryGetValue(imageDict, kCGImagePropertyDPIWidth)

我做错了什么,如何获得字典的所需值?

【问题讨论】:

  • 你能发布你在 xCode 中收到的整个错误吗?
  • 它停止编译并出现该错误:“无法为接受提供的参数的 '__conversion' 找到重载”
  • 上面的错误信息不是副本:“fing”。
  • 对不起,错字。应该是“找到”。手动输入,但如果您喜欢导航器中的副本:Could not find an overload for '__conversion' that accepts the supplied arguments

标签: macos swift core-graphics key-value core-foundation


【解决方案1】:

我发现通过将 CFDictionary '转换'为 Swift 字典来访问属性要容易得多。

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

Swift 2.0 的快速更新(请原谅所有if lets - 我只是快速制作了这段代码):

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)")
                }
            }
        }
    }
}

【讨论】:

  • 我一直在寻找从图像中提取 EXIF 信息的答案。这解决了它。谢谢!
  • 它不适用于 Swift 2.0,因为 CFDictionaryRef 不能转换为 Dictionary
  • @Darrarski 您可以投射到字典吗? (注意它需要被转换为可选)。我更新了一个简单的例子。 (ps。对某事在新版本中不再有效的问题发表评论要好得多——而不是投反对票)。
  • @SoOverIt 看起来事情又发生了变化——在 XCode 7.3 中,我不得不转换为 NSDictionary
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 1970-01-01
  • 2019-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多