I have a list of jpegs that I need to check if they are under 4096px and if the file size is below 4MB. I don't need to display the image so loading the full file and decoding it is a bit overkill.
is it possible to get only height, width from metadata and file size?
on mac os with swift
The file size could be checked by FileManager API.
Image width and height could be checked via CGImageSource functions (ImageIO.framework) without loading the image to memory:
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")
}