2

我在这里有一个演示应用程序https://github.com/rdeert/image-transform-test

导入图像后,您可以捏合、缩放、旋转图像。我想要做的是保存一个640x480看起来与实时预览相同的图像(横向模式)。因此,如果两侧有 100 像素的空白条,我需要在最终输出中使用相同的空白条(适当缩放)。

事实证明,这比我想象的要困难得多。经过几天的工作,我无法完全让它出来。

生成最终图像的魔术方法称为-(void)generateFinalImage

祝你好运!;)

编辑

演示应用截图

绿色矩形代表导入图像可以被捏合、缩放和旋转的实际区域。例如,iPhone 4S 的分辨率为 852x640。

蓝色矩形只是用于调试的实时预览,其纵横比与 640x480 相同。由于 Core Image 非常慢,实时预览可能会变得非常慢。

我想要做的是将绿色矩形中的任何内容转换为640x480图像。请注意,852x640纵横比640x480也略有不同,但这不是一个大问题。

4

1 回答 1

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;
}
于 2012-10-27T00:22:50.187 回答