2

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

fred_
  • 1,486
  • 1
  • 19
  • 31
  • See [How to get the width/height of jpeg file without using library?](https://stackoverflow.com/questions/18264357/how-to-get-the-width-height-of-jpeg-file-without-using-library) – Willeke Jan 11 '19 at 12:53
  • See [How to get the file size given a path?](https://stackoverflow.com/questions/815471/how-to-get-the-file-size-given-a-path) – Willeke Jan 11 '19 at 12:55
  • Really quick, really dirty and needing adapting for swift, but nonetheless... http://www.cplusplus.com/forum/beginner/45217/ – Mark Setchell Jan 11 '19 at 14:24

2 Answers2

1

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")
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
manikal
  • 953
  • 7
  • 30
  • yes for the file size it's ok, but not for height and width, this probably needs to be combined with something else – fred_ Jan 11 '19 at 13:10
  • can you add 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) { return false } } } so I can mark your answer as answered ? – fred_ Jan 11 '19 at 16:30
0

The way to do is is to scan for the image's SOFx marker. The SOF market contains the image size.

On of many sources giving the marker structure:

http://lad.dsc.ufcg.edu.br/multimidia/jpegmarker.pdf

user3344003
  • 20,574
  • 3
  • 26
  • 62