美文网首页
iOS-获取网上图片的Size

iOS-获取网上图片的Size

作者: Simple_Code | 来源:发表于2019-04-17 11:11 被阅读0次

    直接复制可使用

    .h

    #import <Foundation/Foundation.h>
    
    NS_ASSUME_NONNULL_BEGIN
    
    @interface NSURL (AC)
    
    + (CGSize)getImageSizeWithURL:(NSURL *)url;
    end
    
    NS_ASSUME_NONNULL_END
    

    .m

    #import "NSURL+AC.h"
    #import <ImageIO/ImageIO.h>
    #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

          本文链接:https://www.haomeiwen.com/subject/oypgwqtx.html