我刚开始使用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)
我做错了什么,怎样才能达到字典所需的值?
答案 0 :(得分:12)
通过将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 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, 0, nil) as Dictionary? {
let pixelWidth = imageProperties[kCGImagePropertyPixelWidth] as! Int
print("the image width is: \(pixelWidth)")
}
}
}
}
}