【问题标题】:Convert a UIImage to a CIImage to crop to a CGRect. AVFoundation将 UIImage 转换为 CIImage 以裁剪为 CGRect。 AV基金会
【发布时间】:2013-10-21 19:52:39
【问题描述】:

所以我有一个要裁剪的 UIImage。我查看并找到了 CIImage 的 imageByCroppingToRect 方法。因此,我将数据转换为 CIImage 而不是 UIImage,使用指定的方法对其进行裁剪,然后将生成的 CIImage 转换为 UIImage,然后将其显示在 UIImageView 中。

我的代码是

 NSData *data = [[NSData alloc]initWithData:[def objectForKey:@"imageData"]];
//UIImage *normalImage = [[UIImage alloc]initWithData:data];
CIImage *originalImage = [CIImage imageWithData:data];
[originalImage imageByCroppingToRect:CGRectMake(10, 72, 300, 300)];

self.imageView.image = [UIImage imageWithCIImage:originalImage];

问题是图像被旋转了 90 度,我不确定它是否被裁剪。此图像是使用设备的相机捕获的。我使用 AVFoundation 来访问相机。我的会话预设是AVCaptureSessionPresetPhoto。我想这就是我得到缩放的原因。

【问题讨论】:

  • 图像可能被旋转,因为图像处于另一个方向并使用 EXIF 标签翻转。某些图像格式(例如 JPEG)使用有损压缩。旋转并重新保存图像只是为了纠正方向会进一步压缩图像。因此图像本身被保留,但引入元数据表示“该图像应该旋转 90、180 或 270 度”。

标签: ios objective-c uiimage avfoundation ciimage


【解决方案1】:
CGRect rect = CGRectMake(10, 72, 300, 300);
CGImageRef imref = CGImageCreateWithImageInRect([yourOriginalImage CGImage], rect);
UIImage *newSubImage = [UIImage imageWithCGImage:imref];

试试这个。可以帮助你。

编辑:

首先修复您的图像方向: 参考:https://github.com/j3r3miah/mapmatic-ios/blob/master/Mapmatic/UIImage+FixOrientation.m

然后使用上面的代码将图像裁剪为指定的矩形。

【讨论】:

  • 不起作用,我仍然有旋转问题。使用这种技术也可以放大很多。
  • 如果 yourImage 是视网膜图像,那么你需要像 CGRectMake(20, 144, 600, 600) 一样给出 rect
  • 我仍然可以缩放。我正在从相机中获取此图像。我使用 AVFoundation 来访问相机。我的会话预设是AVCaptureSessionPresetPhoto。你认为这就是发生这种情况的原因吗?
  • 可能是问题所在。首先修复图像方向并尝试。 github.com/j3r3miah/mapmatic-ios/blob/master/Mapmatic/…
  • 是的,方向是固定的。谢谢你。我认为图像很大,这就是缩放的原因。我会尝试想出一个新的更合适的矩形大小
【解决方案2】:

不是真正回答你的问题,而是回答你的问题

https://github.com/mbcharbonneau/UIImage-Categories

尤其是这个文件:https://github.com/mbcharbonneau/UIImage-Categories/blob/master/UIImage%2BResize.m

- (UIImage *)croppedImage:(CGRect)bounds {
    CGFloat scale = MAX(self.scale, 1.0f);
    CGRect scaledBounds = CGRectMake(bounds.origin.x * scale, bounds.origin.y * scale, bounds.size.width * scale, bounds.size.height * scale);
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], scaledBounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:UIImageOrientationUp];
    CGImageRelease(imageRef);
    return croppedImage;
}

您将在那里找到裁剪图像所需的一切

【讨论】:

  • 是有道理的。谢谢
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 2017-04-09
  • 2020-11-19
  • 1970-01-01
相关资源
最近更新 更多