ALAssetsLibrary aspect Ratio Thumbnail iOS 4
Posted
技术标签:
【中文标题】ALAssetsLibrary aspect Ratio Thumbnail iOS 4【英文标题】:ALAssetLibrary aspectRatioThumbnail iOS4 【发布时间】:2012-09-22 15:41:59 【问题描述】:我正在处理一个需要浏览和显示 iPhone 画廊中的图片的项目。
我使用 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);
【问题讨论】:
【参考方案1】:上面的代码有很多不必要的复制。相反,只需以屏幕分辨率(小于完整图像大小)加载图像并从那里缩小为缩略图:
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();
运行此代码后,thumbnail 将有一个与 aspectRatioThumbnail 等效的 UIImage。
【讨论】:
以上是关于ALAssetsLibrary aspect Ratio Thumbnail iOS 4的主要内容,如果未能解决你的问题,请参考以下文章
保存图像元数据 PHPhotoLibrary 与 ALAssetsLibrary