macos – 使用swift读取CFDictionary中的值

前端之家收集整理的这篇文章主要介绍了macos – 使用swift读取CFDictionary中的值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚开始使用swift和cocoa.我正在尝试创建一个执行图像处理的基本应用程序.

我已经获得了图像的所有信息:

let imageRef:CGImageSourceRef = CGImageSourceCreateWithURL(url,nil).takeUnretainedValue()
let imageDict:CFDictionaryRef = CGImageSourceCopyPropertiesAtIndex(imageRef,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)

我做错了什么,怎样才能达到字典所需的值?

我发现通过将CFDictionary“转换”为Swift字典来访问属性要容易得多.
let imageSource = CGImageSourceCreateWithURL(imageURL,nil)
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource,nil) as Dictionary
let dpiWidth = imageProperties[kCGImagePropertyDPIWidth] as NSNumber

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

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,nil) as Dictionary? {
                    let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
                    print("the image width is: \(pixelWidth)")
                }
            }
        }
    }
}
原文链接:https://www.f2er.com/swift/320244.html

猜你在找的Swift相关文章