ios - 缩放 UIImage/CGImage

标签 ios image-processing uiimage core-graphics cgimage

我正在使用 AVFoundation 在相机应用程序中实现缩放功能。我正在像这样缩放我的预览 View :

[videoPreviewView setTransform:CGAffineTransformMakeScale(cameraZoom, cameraZoom)];

现在,拍完照片后,我想在将照片保存到相机胶卷之前使用 cameraZoom 值缩放/裁剪照片。我应该如何最好地做到这一点?

编辑:使用 Justin 的回答:

CGRect imageRect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);

CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], imageRect);

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

CGContextScaleCTM(bitmapContext, scale, scale);
CGContextDrawImage(bitmapContext, imageRect, imageRef);

CGImageRef zoomedCGImage = CGBitmapContextCreateImage(bitmapContext);

UIImage* zoomedImage = [[UIImage alloc] initWithCGImage:imageRef];

它正在缩放图像,但它并没有占据图像的中心,而是似乎占据了右上角的区域。 (我不是肯定的)。

另一个问题(我应该在 OP 中更清楚)是图像保持相同的分辨率,但我宁愿将其裁剪掉。

最佳答案

+ (UIImage*)croppedImageWithImage:(UIImage *)image zoom:(CGFloat)zoom
{
    CGFloat zoomReciprocal = 1.0f / zoom;

    CGPoint offset = CGPointMake(image.size.width * ((1.0f - zoomReciprocal) / 2.0f), image.size.height * ((1.0f - zoomReciprocal) / 2.0f));
    CGRect croppedRect = CGRectMake(offset.x, offset.y, image.size.width * zoomReciprocal, image.size.height * zoomReciprocal);

    CGImageRef croppedImageRef = CGImageCreateWithImageInRect([image CGImage], croppedRect);

    UIImage* croppedImage = [[UIImage alloc] initWithCGImage:croppedImageRef scale:[image scale] orientation:[image imageOrientation]];

    CGImageRelease(croppedImageRef);

    return croppedImage;
}

关于ios - 缩放 UIImage/CGImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8959293/

相关文章:

ios - Interface Builder Storyboard 编译失败?

ios - PdfView 中的 PdfDocument 因 Objective C 中无法识别的选择器实例而崩溃

opencv - Android:平滑随机形状位图的边缘

objective-c - 如何用颜色填充 imageview 中的空白(未被图像覆盖)?

iphone - 将 2 个 UIImage 合并为一个,其中一个被旋转

ios - 在特定的 CollectionViewCell 中隐藏 View

ios - 如何使用 swift 等待登录 View 的 api 响应值

python - 如何在OpenCV中检测数独网格板

python - 如何使用 Pillow 的 Image.load() 函数生成蒙版

ios - 将图像文件保存到 Swift 中的应用程序文档目录。即使部署在设备上,App 文档目录的 url 是否也会改变?