将多个图像合并为1
问题描述:
我试图将其他一些预设图像与从相机拍摄的照片叠加在一起。问题是,来自相机的图像可能是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);
所有这些工作,但本质上,加倍当前内存使用量。
反正是有构成它们放在一起,而无需创建新的情境?也许将所有图像保存在文件系统中并在那里进行合并而不会真正消耗大量内存?或者,甚至可能渲染到每个磁贴的文件系统磁贴?
任何建议或指针在哪里,我从这个去?
感谢
答
看看下面的代码。您可以将多个图像发送到以下方法,但是当您遇到内存问题时,我建议您重复调用相同的方法来合并多个图像。但这个过程可能需要更多时间。
-(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;
}
希望这会有所帮助。