2012-09-22 22 views
0

我正在研究需要瀏覽和顯示iPhone畫廊中存在的圖片的項目。ALAsset庫方面比率縮略圖iOS4

我使用ALAssetLibrary來做到這一點。要生成縮略圖,我使用「aspectRatioThumbnail」。一切工作順利,我的3GS iOS 5平滑但這些方法在iOS4中不存在。

我嘗試使用此功能手動生成縮略圖比率圖像,但由於內存警告而崩潰。日誌告訴我,生成的圖像大小不尊重給定的最大大小120的限制。

任何想法?

NSDate* firstDate = [NSDate date]; 
    uint8_t* buffer = (Byte*)malloc(_asset.defaultRepresentation.size); 

    NSUInteger length = [_asset.defaultRepresentation getBytes:buffer fromOffset:0.0 length:_asset.defaultRepresentation.size error:nil]; 

NSData* data = [[NSData alloc] initWithBytesNoCopy:buffer length:_asset.defaultRepresentation.size freeWhenDone:YES]; 
            nil]; 

     NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys: 
          (id)kCFBooleanTrue, kCGImageSourceShouldAllowFloat, 
          (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailWithTransform, 
          (id)kCFBooleanTrue, kCGImageSourceCreateThumbnailFromImageAlways, 
          [NSNumber numberWithInt:120], kCGImageSourceThumbnailMaxPixelSize, 
          nil]; 

     CGImageSourceRef sourceRef = CGImageSourceCreateWithData((CFDataRef)data, (CFDictionaryRef) options); 
     CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(sourceRef, 0, NULL); 

     CGImageRef imageRef = CGImageSourceCreateImageAtIndex(sourceRef, 0, imageProperties); 

     image = [UIImage imageWithCGImage:imageRef]; 

     NSTimeInterval tic = [[NSDate date] timeIntervalSinceDate:firstDate]; 
     NSLog(@"Thumbnail generation from ios4 method %f [size %f * %f", tic, image.size.width, image.size.height); 

     [data release]; 
     CFRelease(sourceRef); 
     CFRelease(imageRef); 
     CFRelease(imageProperties); 

回答

2

上面的代碼有很多不必要的複製。相反,只需加載在屏幕分辨率(小於完整的圖像大小)的圖像,並從那裏向縮小的縮略圖:

CGImageRef img = [[asset defaultRepresentation] fullScreenImage]; 
int w = CGImageGetWidth(img); 
int h = CGImageGetHeight(img); 
float scale = 120/(float)(MAX(w, h)); 
CGSize newsize = CGSizeMake(w * scale, h * scale); 

UIGraphicsBeginImageContext(newsize); 
CGContextRef ctx = UIGraphicsGetCurrentContext(); 
CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); 
CGContextTranslateCTM(ctx, 0, newsize.height); 
CGContextScaleCTM(ctx, 1.0, -1.0); 
CGContextDrawImage(ctx, CGRectMake(0, 0, newsize.width, newsize.height), iref); 
UIImage* thumbnail = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

運行此代碼後,縮略圖將有一個UIImage這相當於aspectRatioThumbnail。