CGImageSourceRef imageSource = CGImageSourceCreateWithURL返回NULL

时间:2013-05-23 12:11:29

标签: objective-c cgimagesource

我想获取图像的大小而不加载它,所以我使用下面的代码

-(float)gettingimagedimensions:(NSString*)url{
    NSURL *imageFileURL = [NSURL fileURLWithPath:url];
    //CGImageSourceRef imageSource = CGImageSourceCreateWithURL(imageFileURL, NULL);
    CGImageSourceRef imageSource = CGImageSourceCreateWithURL((__bridge CFURLRef)imageFileURL, NULL);
    if (imageSource == NULL) {
        // Error loading image

        return 0;
    }

    CGFloat width = 0.0f, height = 0.0f;
    CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, NULL);
    if (imageProperties != NULL) {
        CFNumberRef widthNum  = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelWidth);
        if (widthNum != NULL) {
            CFNumberGetValue(widthNum, kCFNumberFloatType, &width);
        }

        CFNumberRef heightNum = CFDictionaryGetValue(imageProperties, kCGImagePropertyPixelHeight);
        if (heightNum != NULL) {
            CFNumberGetValue(heightNum, kCFNumberFloatType, &height);
        }

        CFRelease(imageProperties);
    }

    NSLog(@"Image dimensions: %.0f x %.0f px", width, height);

    return height;
}

问题是imageSource始终为NULL 有没有人知道,为什么它不起作用!!

请注意,URL是JPG或PNG图像的有效链接

1 个答案:

答案 0 :(得分:1)

您是否启用了ARC?我没有,我的工作代码如下:

NSURL * imageFileURL = [NSURL fileURLWithPath:fp];
CGImageSourceRef imageSource = CGImageSourceCreateWithURL((CFURLRef)imageFileURL, NULL);

请注意缺少__bridge。完成btw后,我在CFRelease上致电imageSource