Swift 无需解码即可快速读取jpeg的高度、宽度和文件大小

Swift 无需解码即可快速读取jpeg的高度、宽度和文件大小,swift,macos,jpeg,nsfilemanager,Swift,Macos,Jpeg,Nsfilemanager,我有一个JPEG的列表,我需要检查它们是否低于4096px,文件大小是否低于4MB。我不需要显示图像,因此加载完整文件并对其进行解码有点过头了 是否可以从元数据和文件大小中仅获取高度、宽度 在使用swift的mac os上,文件大小可以通过以下方式进行检查: 无需将图像加载到内存,即可通过函数(ImageIO.framework)检查图像的宽度和高度: do { let attribute = try FileManager.default.attributesOfItem(atPath

我有一个JPEG的列表,我需要检查它们是否低于4096px,文件大小是否低于4MB。我不需要显示图像,因此加载完整文件并对其进行解码有点过头了

是否可以从元数据和文件大小中仅获取高度、宽度


在使用swift的mac os上,文件大小可以通过以下方式进行检查:

无需将图像加载到内存,即可通过函数(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")
}
do{
让attribute=try FileManager.default.attributesOfItem(atPath:filePath)
//文件大小
将fileSize=attribute[FileAttributeKey.size]设为!Int
//宽度和高度
让imageFileUrl=URL(fileURLWithPath:filePath)
如果让imageSource=CGImageSourceCreateWithURL(imageFileUrl作为CFURL,nil){
如果让imageProperties=CGImageSourceCopyPropertiesAtIndex(imageSource,0,nil)作为字典{
设width=imageProperties[kCGImagePropertyPixelWidth]为!Int
设height=imageProperties[kCGImagePropertyPixelHeight]为!Int
如果(高度>4096 | |宽度>4096 | |高度<256 | |宽度<256){
打印(“大小无效”)
}否则{
打印(“大小有效”)
}
}
}
}抓住{
打印(“无法读取文件属性”)
}

方法是扫描图像的SOFx标记。软件市场包含图像大小

在给出标记结构的许多来源中:


看,速度非常快,非常脏,需要适应swift,但尽管如此。。。是的,对于文件大小没有问题,但对于高度和宽度没有问题,这可能需要与其他内容结合使用。如果让imageSource=CGImageSourceCreateWithURL(imageFileUrl作为CFURL,nil){如果让imageProperties=CGImageSourceCopyPropertiesAtIndex,可以添加let imageFileUrl=URL(fileURLWithPath:filePath)(imageSource,0,nil)作为字典?{let width=imageProperties[kCGImagePropertyPixelWidth]作为!Int let height=imageProperties[kCGImagePropertyPixelHeight]作为!Int if(height>4096 | width>4096 | height<256 | | width<256){return false}}这样我就可以把你的答案标记为已回答?