accessing UIImage properties without loading in memory the image

后端 未结 3 1820
余生分开走
余生分开走 2020-12-07 15:53

As you know the iphone guidelines discourage loading uiimages that are greater than 1024x1024.

The size of the images that i would have to load varies, and i would l

3条回答
  •  孤城傲影
    2020-12-07 16:43

    Swift 3 version of the answer:

    import Foundation
    import ImageIO
    
    func sizeForImage(at url: URL) -> CGSize? {
    
        guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil)
            , let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [AnyHashable: Any]
            , let pixelWidth = imageProperties[kCGImagePropertyPixelWidth as String]
            , let pixelHeight = imageProperties[kCGImagePropertyPixelHeight as String]
            , let orientationNumber = imageProperties[kCGImagePropertyOrientation as String]
            else {
                return nil
        }
    
        var width: CGFloat = 0, height: CGFloat = 0, orientation: Int = 0
    
        CFNumberGetValue(pixelWidth as! CFNumber, .cgFloatType, &width)
        CFNumberGetValue(pixelHeight as! CFNumber, .cgFloatType, &height)
        CFNumberGetValue(orientationNumber as! CFNumber, .intType, &orientation)
    
        // Check orientation and flip size if required
        if orientation > 4 { let temp = width; width = height; height = temp }
    
        return CGSize(width: width, height: height)
    }
    

提交回复
热议问题