我有一个jpeg列表,我需要检查它们是否在4096px以下以及文件大小是否在4MB以下。我不需要显示图像,因此加载完整文件并对其进行解码有点矫kill过正。
是否可以从元数据和文件大小中仅获取高度,宽度?
在Mac OS上迅速
答案 0 :(得分:1)
FileManager 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")
}
答案 1 :(得分:0)