假设我有一个从某个URL
加载的CGImage
,我想通过CGImageSourceCopyPropertiesAtIndex
提取其属性:
// Playground
import SwiftUI
func printPropertiesOf(_ image: CGImage) {
guard let dataProvider = image.dataProvider else {
print("Couldn't get the data provider.")
return
}
guard let data = dataProvider.data else {
print("Couldn't get the data.")
return
}
guard let source = CGImageSourceCreateWithData(data, nil) else {
print("Couldn't get the source.")
return
}
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) else {
print("Couldn't get the properties.")
return
}
print(properties)
}
let url = Bundle.main.url(forResource: "Landscape/Landscape_0", withExtension: "jpg")!
let source = CGImageSourceCreateWithURL(url as CFURL, nil)!
let cgImage = CGImageSourceCreateImageAtIndex(source, 0, nil)!
printPropertiesOf(cgImage)
输出:
无法获取属性。
但是,如果我使用图像所在的URL
而不是CGImage
:
// Playground
import SwiftUI
func printPropertiesOfImageIn(_ url: URL) {
guard let data = try? Data(contentsOf: url) else {
print("Couldn't get the data.")
return
}
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else {
print("Couldn't get the source.")
return
}
guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) else {
print("Couldn't get the properties.")
return
}
print(properties)
}
let url = Bundle.main.url(forResource: "Landscape/Landscape_0", withExtension: "jpg")!
let source = CGImageSourceCreateWithURL(url as CFURL, nil)!
let cgImage = CGImageSourceCreateImageAtIndex(source, 0, nil)!
printPropertiesOfImageIn(url)
输出:
{
ColorModel = RGB;
DPIHeight = 72;
DPIWidth = 72;
Depth = 8;
PixelHeight = 1200;
PixelWidth = 1800;
"{JFIF}" = {
DensityUnit = 1;
JFIFVersion = (
1,
0,
1
);
XDensity = 72;
YDensity = 72;
};
"{TIFF}" = {
Orientation = 0;
ResolutionUnit = 2;
XResolution = 72;
YResolution = 72;
};
}
有没有办法从
CGImage
本身检索元数据, 而不必依赖其源 URL?如果没有,有没有办法找出给定的来源
URL
CGImage
?
(注意:上述示例中使用的图像可以在此处找到。
CGImage
应该是完全原始的位图数据。一组最少的未压缩数据,用于直观地呈现图像。来自文档"位图图像或图像蒙版"。
我真的很惊讶你能够以两种不同的方式使用CGImageSourceCreateWithData
构建一个源:
-
在第一种情况下,您直接从原始未压缩数据创建它,这是您的
CGImage
。预计它绝对没有标题或有关如何显示的其他信息。 -
在第二种情况下,您是从JPEG数据创建它,JPEG数据是带有可能包含大量不同信息的标题的压缩数据。例如,某些信息可能完全不相关,例如拍摄图像的位置或拍摄日期的坐标。
因此,您在第二种情况下显示的其他信息可能会被系统用于构造CGImage
对象(例如编码(。但这不是需要附加到CGImage
以显示它的信息,因为它已经准备好(解码(以进行演示。
在你的标题中,你说"CGImage没有属性/元数据(CGImageProperties("。没有"CGImageProperties"这样的东西,有"CGImageSourceProperties"。因此,它是具有属性的源。
所以我相信这些属性不是复制的,也没有办法单独从CGImage
获得它们。不过,您还可以直接从CGImage
获得其他属性:
- cgImage.width
- cgImage.height
- cgImage.alphaInfo
- cgImage.bitmapInfo
- cgImage.bitsPerComponent
- cgImage.colorSpace
- 。
您可以在此处查看更多内容。