iOS-获取网上图片的Size

直接复制可使用

.h

#import 

NS_ASSUME_NONNULL_BEGIN

@interface NSURL (AC)

+ (CGSize)getImageSizeWithURL:(NSURL *)url;
end

NS_ASSUME_NONNULL_END

.m

#import "NSURL+AC.h"
#import 
#import "SDImageCache.h"

@implementation NSURL (AC)

+ (CGSize)getImageSizeWithURL:(NSURL *)url{
   
    if (![url isKindOfClass:[NSURL class]]||(url == nil)) {
        return CGSizeZero;
    }

    CGFloat width = 0.0f, height = 0.0f;
    UIImage *img = [[SDImageCache sharedImageCache]imageFromCacheForKey:url.absoluteString];
    if (img) {
        width = img.size.width;
        height = img.size.height;
    }else{
        CGImageSourceRef imageSourceRef =     CGImageSourceCreateWithURL((CFURLRef)url, NULL);
        if (imageSourceRef) {
            CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSourceRef, 0, NULL);
            if (imageProperties != NULL) {
                CFNumberRef widthNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
                //判断设备是否为64位
#if defined(__LP64__) && __LP64__
                if (widthNumberRef != NULL) {
                    CFNumberGetValue(widthNumberRef, kCFNumberFloat64Type, &width);
                }
                CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
                if (heightNumberRef != NULL) {
                    CFNumberGetValue(heightNumberRef, kCFNumberFloat64Type, &height);
                }
#else
                if (widthNumberRef != NULL) {
                    CFNumberGetValue(widthNumberRef, kCFNumberFloat32Type, &width);
                }
                CFNumberRef heightNumberRef = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
                if (heightNumberRef != NULL) {
                    CFNumberGetValue(heightNumberRef, kCFNumberFloat32Type, &height);
                }
#endif
                
                CFRelease(imageProperties);
            }
            CFRelease(imageSourceRef);
            NSLog(@"Image dimensions: %.0f x %.0f px", width, height);
        }}
    return CGSizeMake(width, height);
}

@end

你可能感兴趣的:(iOS-获取网上图片的Size)