美文网首页
Swift 获取网络图片大小

Swift 获取网络图片大小

作者: jsone | 来源:发表于2020-07-22 14:26 被阅读0次

    开发中经常遇到根据图片大小动态设置Cell或者ImageView的宽高的需求,通过图片的网络地址直接获取图片的大小就可以实现这个需求
    Swift代码:

    let imageSource = CGImageSourceCreateWithURL(URL(string: imageURL)! as CFURL, nil)
    if let result = CGImageSourceCopyPropertiesAtIndex(imageSource!, 0, nil) as? Dictionary<String, Any> {
        print("😃\(result)")
        if let width = result["PixelWidth"] as? CGFloat, let height = result["PixelHeight"] as? CGFloat {
            print("😃width:\(width),height:\(height)")
        }
    }
    

    输出结果:

    😃["PixelHeight": 1152, "{JFIF}": {
        DensityUnit = 0;
        JFIFVersion =     (
            1,
            0,
            1
        );
        XDensity = 1;
        YDensity = 1;
    }, "Depth": 8, "ColorModel": RGB, "PixelWidth": 1728]
    😃width:1728.0,height:1152.0
    

    Objective-C代码:

    #import <ImageIO/ImageIO.h>
    
    NSMutableString *imageURL = [NSMutableString stringWithFormat:@"http://www.myimageurl.com/image.png"];
    
    CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)[NSURL URLWithString:imageURL], NULL);
    NSDictionary* imageHeader = (__bridge NSDictionary*) CGImageSourceCopyPropertiesAtIndex(source, 0, NULL);
    NSLog(@"Image header %@",imageHeader);
    CGFloat pixelHeight = [[imageHeader objectForKey:@"PixelHeight"] floatValue];
    CGFloat pixelWidth  = [[imageHeader objectForKey:@"PixelWidth"] floatValue];
    CGSize size = CGSizeMake(pixelWidth, pixelHeight);
    

    参考文章:
    iOS获取网络图片的大小

    相关文章

      网友评论

          本文标题:Swift 获取网络图片大小

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