将多张图片合并成一张图片

3

我正在尝试将从相机拍摄的图片与其他预设图像叠加。问题在于,相机拍摄的照片可能有8百万像素,这在内存使用方面非常庞大。有些覆盖层可能试图覆盖整个图像。

我尝试了多种方法将它们合并为一张图片。

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个回答

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;
}

希望这有所帮助。

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