默认表示法中的ALAsset全屏图像未能返回全屏图像。

7

在我的应用程序中,我将图像保存为资源并存储到相册中。我也想检索它们并在全屏中显示它们。我使用以下代码:

ALAsset *lastPicture = [scrollArray objectAtIndex:iAsset]; 

ALAssetRepresentation *defaultRep = [lastPicture defaultRepresentation];

UIImage *image = [UIImage imageWithCGImage:[defaultRep fullScreenImage] 
                                          scale:[defaultRep scale] orientation:
    (UIImageOrientation)[defaultRep orientation]];

问题在于返回的图像为nil。我在ALAssetRepresentation参考文献中读到,当图像不合适时,会返回nil。

我将这个图像放到一个大小为iPad屏幕的UIImageView中。我想知道你能否帮我解决这个问题?

提前感谢您。


从这段代码来看,一切都很正常,而且在我的应用程序中,这段代码可以提供所有的图像。我可以说,检索到的资源将是nil,或者那段代码有问题,而不是这段代码。 - The iOSDev
1个回答

7
我不太喜欢使用fullScreenImage或fullResolutionImage。我发现,即使您立即释放UIImage,在对多个资源进行队列操作时,内存使用量也会显著增加,这是不应该的。而且,当使用fullScreenImage或fullResolutionImage时,返回的UIImage仍然是压缩的,这意味着它将在第一次绘制之前被解压缩,因此在主线程上运行,这将阻塞您的UI。
我更喜欢使用这种方法。
-(UIImage *)fullSizeImageForAssetRepresentation:(ALAssetRepresentation *)assetRepresentation
{
    UIImage *result = nil;
    NSData *data = nil;

    uint8_t *buffer = (uint8_t *)malloc(sizeof(uint8_t)*[assetRepresentation size]);
    if (buffer != NULL) {
        NSError *error = nil;
        NSUInteger bytesRead = [assetRepresentation getBytes:buffer fromOffset:0 length:[assetRepresentation size] error:&error];
        data = [NSData dataWithBytes:buffer length:bytesRead];

        free(buffer);
    }

    if ([data length])
    {
        CGImageSourceRef sourceRef = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil);

        NSMutableDictionary *options = [NSMutableDictionary dictionary];

        [options setObject:(id)kCFBooleanTrue forKey:(id)kCGImageSourceShouldAllowFloat];
        [options setObject:(id)kCFBooleanTrue forKey:(id)kCGImageSourceCreateThumbnailFromImageAlways];
        [options setObject:(id)[NSNumber numberWithFloat:640.0f] forKey:(id)kCGImageSourceThumbnailMaxPixelSize];
        //[options setObject:(id)kCFBooleanTrue forKey:(id)kCGImageSourceCreateThumbnailWithTransform];

        CGImageRef imageRef = CGImageSourceCreateThumbnailAtIndex(sourceRef, 0, (__bridge CFDictionaryRef)options);

        if (imageRef) {
            result = [UIImage imageWithCGImage:imageRef scale:[assetRepresentation scale] orientation:(UIImageOrientation)[assetRepresentation orientation]];
            CGImageRelease(imageRef);
        }

        if (sourceRef)
            CFRelease(sourceRef);
    }

    return result;
}

您可以像这样使用它:
// Get the full image in a background thread
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

    UIImage* image = [self fullSizeImageForAssetRepresentation:asset.defaultRepresentation];
    dispatch_async(dispatch_get_main_queue(), ^{

    // Do something with the UIImage
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接