我在这里有一个演示应用https://github.com/rdetert/image-transform-test
导入图像后,您可以捏合,缩放,旋转图像。我想要做的是保存一个看起来与实时预览相同的640x480
图像(横向模式)。因此,如果两侧有100px的空白条,我需要在最终输出中使用相同的空条(适当缩放)。
事实证明这比我想象的要困难得多。经过几天的努力,我无法让它立即出来。
生成最终图像的神奇方法称为-(void)generateFinalImage
修改
绿色矩形表示可以捏合,缩放和旋转导入图像的实际区域。例如,iPhone 4S的分辨率为852x640。
蓝色矩形只是用于调试的实时预览,其宽高比与640x480相同。由于Core Image非常慢,实时预览可能会变慢。
我想要做的是将绿色矩形中的任何内容转换为640x480
图像。请注意,852x640
的宽高比与640x480
略有不同,但这不是一个大问题。
答案 0 :(得分:2)
您的目标是获取您正在编辑的内容的精确副本,但是原始图像的大小是多少? 我想这可以通过以下方式获得:
- (UIImage *)padImage:(UIImage *)img to:(CGSize)size
{
if (size.width < img.size.width && size.height < img.size.height) return img;
size.width = MAX(size.width, img.size.width);
size.height = MAX(size.height, img.size.height);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, size.width, size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGRect centeredRect = CGRectMake((size.width - img.size.width)/2.0, (size.height - img.size.height)/2.0, img.size.width, img.size.height);
CGContextDrawImage(context, centeredRect, [img CGImage]);
CGImageRef imageRef = CGBitmapContextCreateImage(context);
CGColorSpaceRelease(colorSpace);
CGContextRelease(context);
UIImage *paddedImage = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return paddedImage;
}
// final image size must be 640x480
- (void)generateFinalImage
{
float rotatableCanvasWidth = 495.0;
float rotatableCanvasHeight = 320.0;
UIImage *tmp = self.importedRawImage;
CGSize size = self.importedRawImage.size;
NSLog(NSStringFromCGSize(size));
tmp = [self padImage:tmp to:CGSizeMake(rotatableCanvasWidth, rotatableCanvasHeight)];
CIImage *ciImage = [[CIImage alloc] initWithImage:[tmp imageWithTransform:self.importedImageView.transform]];
CGPoint center = CGPointMake(size.width / 2.0, size.height / 2.0);
CIContext *context = [CIContext contextWithOptions:nil];
CGRect r = ciImage.extent;
r.origin.x = (r.size.width - rotatableCanvasHeight) / 2.0;
r.origin.y = (r.size.height - rotatableCanvasWidth) / 2.0;
r.size.width = rotatableCanvasHeight;
r.size.height = rotatableCanvasWidth;
self.finalImage = [UIImage imageWithCGImage:[context createCGImage:ciImage fromRect:r] scale:1.0 orientation:UIImageOrientationUp];
self.finalImage = [self.finalImage resizedImage:CGSizeMake(100.0f, 134.0f) interpolationQuality:kCGInterpolationHigh];
self.previewImageView.image = self.finalImage;
}