我有一个jpeg列表,我需要检查它们是否低于4096px以及文件大小是否低于4MB。我不需要显示图像,因此加载完整文件并对其进行解码有点矫枉过正。
是否可以仅从元数据和文件大小中获得高度、宽度?
在装有 Swift 的 Mac OS 上
文件大小可以通过文件管理器API检查。
图像宽度和高度可以通过CGImageSource函数(ImageIO.framework)进行检查,而无需将图像加载到内存中:
do {
let attribute = try FileManager.default.attributesOfItem(atPath: filePath)
// Filesize
let fileSize = attribute[FileAttributeKey.size] as! Int
// Width & Height
let imageFileUrl = URL(fileURLWithPath: filePath)
if let imageSource = CGImageSourceCreateWithURL(imageFileUrl as CFURL, nil) {
if let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as Dictionary? {
let width = imageProperties[kCGImagePropertyPixelWidth] as! Int
let height = imageProperties[kCGImagePropertyPixelHeight] as! Int
if (height > 4096 || width > 4096 || height < 256 || width < 256) {
print("Size not valid")
} else {
print("Size is valid")
}
}
}
} catch {
print("File attributes cannot be read")
}
方法是扫描图像的 SOFx 标记。SOF 市场包含图像大小。
在许多给出标记结构的来源中:
http://lad.dsc.ufcg.edu.br/multimidia/jpegmarker.pdf