2013-03-21 122 views
3

我試圖將其他一些預設圖像與從相機拍攝的照片疊加在一起。問題是,來自相機的圖像可能是8MP,它在內存使用方面是巨大的。某些疊加層可能會嘗試覆蓋整個圖像。將多個圖像合併爲1

我試過多種方式將它們全部合併成一個圖像。

UIGraphicsBeginImageContextWithOptions(_imageView.image.size, NO, 1.0f); 
[_containerView.layer renderInContext:UIGraphicsGetCurrentContext()]; 
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); 

CGContextDrawImage(UIGraphicsGetCurrentContext(), (CGRect){CGPointZero, _imageView.image.size}, _imageView.image.CGImage); 
CGContextDrawImage(UIGraphicsGetCurrentContext(), (CGRect){CGPointZero, _imageView.image.size}, *other image views*); 

UIImage* image = _imageView.image; 
CGImageRef imageRef = image.CGImage; 

size_t imageWidth = (size_t)image.size.width; 
size_t imageHeight = (size_t)image.size.height; 

CGContextRef context = CGBitmapContextCreate(NULL, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), CGImageGetColorSpace(imageRef), CGImageGetBitmapInfo(imageRef)); 

CGRect rect = (CGRect){CGPointZero, {imageWidth, imageHeight}}; 
CGContextDrawImage(context, rect, imageRef); 
CGContextDrawImage(context, rect, **other images**); 
CGImageRef newImageRef = CGBitmapContextCreateImage(context); 
CGContextRelease(context); 

UIImage* resultImage = nil; 

NSURL* url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"x.jpg"]]; 
CFURLRef URLRef = CFBridgingRetain(url); 
CGImageDestinationRef destination = CGImageDestinationCreateWithURL(URLRef, kUTTypeJPEG, 1, NULL); 
if (destination != NULL) 
{ 
    CGImageDestinationAddImage(destination, newImageRef, NULL); 
    if (CGImageDestinationFinalize(destination)) 
    { 
     resultImage = [[UIImage alloc] initWithContentsOfFile:url.path]; 
    } 
    CFRelease(destination); 
} 
CGImageRelease(newImageRef); 

所有這些工作,但本質上,加倍當前內存使用量。

反正是有構成它們放在一起,而無需創建新的情境?也許將所有圖像保存在文件系統中並在那裏進行合併而不會真正消耗大量內存?或者,甚至可能渲染到每個磁貼的文件系統磁貼?

任何建議或指針在哪裏,我從這個去?

感謝

回答

1

看看下面的代碼。您可以將多個圖像發送到以下方法,但是當您遇到內存問題時,我建議您重複調用相同的方法來合併多個圖像。但這個過程可能需要更多時間。

-(CGImageRef)mergedImageFromImageOne:(UIImage *)imageOne andImageTwo:(UIImage *)imageTwo 
{ 
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; 
    CGSize imageSize = imageOne.size; 

    UIGraphicsBeginImageContext(sizeVideo); 

    [imageOne drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height)]; 

    [imageTwo drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height) alpha:1]; 

    CGImageRef imageRefNew = CGImageCreateWithImageInRect(UIGraphicsGetImageFromCurrentImageContext().CGImage, CGRectMake(0,0,imageOne.width,imageOne.height)); 

    UIGraphicsEndImageContext(); 

    [pool release]; 

    return imageRefNew; 
} 

希望這會有所幫助。