2012-07-09 42 views
6

在我的應用程序中,我將圖像作爲資產保存到相冊中。我也想要檢索它們並以全屏顯示它們。我使用下面的代碼:defaultRepresentation ALAsset上的fullScreenImage不返回全屏圖像

ALAsset *lastPicture = [scrollArray objectAtIndex:iAsset]; 

ALAssetRepresentation *defaultRep = [lastPicture defaultRepresentation]; 

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

的問題是,返回的圖像是。我已閱讀ALAssetRepresentation參考,當圖像不適合時,返回nil。

我把這個圖像一個UIImageView它具有iPad屏幕的大小。我想知道你能否幫我解決這個問題?

預先感謝您。

+0

從這個代碼看起來沒什麼問題的,在我的應用程序的代碼也是打工的所有圖像罰款。我可以說,檢索到的資產將是零,或者該代碼存在一些問題,而不是這一個 – 2012-07-09 11:15:54

回答

8

我不是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 
    }); 
});