import ImageIO
extension UIImage {
/**
* 根据图片url获取网络图片尺寸
*/
class func getSizeWithURL(_ URL: Any?) -> CGSize {
var url: URL? = nil
if (URL is URL) {
url = URL as? URL
}
if (URL is String) {
url = URL(string: URL as? String ?? "")
}
if URL == nil {
return CGSize.zero
}
let imageSourceRef = CGImageSourceCreateWithURL(url as? CFURL?, nil)
var width: CGFloat = 0
var height: CGFloat = 0
if imageSourceRef != nil {
let imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, nil)
//以下是对手机32位、64位的处理(由网友评论区拿到的:小怪兽饲养猿)
if imageProperties != nil {
let widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth)
#if __LP64__ && __LP64__
if widthNumberRef != nil {
CFNumberGetValue(widthNumberRef, CFNumberType.float64Type, &width)
}
let heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight)
if heightNumberRef != nil {
CFNumberGetValue(heightNumberRef, CFNumberType.float64Type, &height)
}
#else
if widthNumberRef != nil {
CFNumberGetValue(widthNumberRef, CFNumberType.float32Type, &width)
}
let heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight)
if heightNumberRef != nil {
CFNumberGetValue(heightNumberRef, CFNumberType.float32Type, &height)
}
#endif
}
}
return CGSize(width: width, height: height)
}
}