【问题标题】:CG raster data too large for one imageCG 栅格数据对于一张图像来说太大了
【发布时间】:2017-09-21 12:20:24
【问题描述】:

我试图旋转用相机拍摄的 2448x3264 的 UIImage。当我这样做时,内存大约达到 120Mb,大约持续 3/4 秒,然后恢复到正常状态。问题是,在内存较少的设备(例如,ipod touch)中,应用程序崩溃。即使没有,我认为它不应该为一张图像使用那么多内存。发生这种情况时,Iphone 5 也会滞后。

根据this答案中的评论,使用UIGraphicsGetCurrentContext()后解压内存的字节大小应该是width * height * CGImageGetBitsPerComponent(image.CGImage) / 8 bytes,所以图片应该占用8Mb,而不是120.

知道为什么会发生这种情况以及如何解决吗?

这是返回旋转图像的 UIImage 分类方法:

- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees {
    CGFloat radian = (CGFloat) (degrees * (M_PI/ 180.0f));
    CGSize rotatedSize = [self rotatedImageSize:degrees];

    // Create the bitmap context
    UIGraphicsBeginImageContextWithOptions(rotatedSize, NO, 0);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();

    CGPoint contextCenter = CGPointMake(rotatedSize.width/2.0f, 
rotatedSize.height/2.0f);
    CGContextTranslateCTM(bitmap, contextCenter.x, contextCenter.y);

    //   // Rotate the image context
    CGContextRotateCTM(bitmap, radian);
    // Now, draw the rotated/scaled image into the context
    [self drawInRect:CGRectMake(-self.size.width/2.0f, -
self.size.height/2.0f, self.size.width, self.size.height)];

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

这是来自仪器的证明,即光栅数据是导致内存峰值的原因,就在执行旋转方法时:

Instruments proof

【问题讨论】:

    标签: ios objective-c uiimage core-graphics


    【解决方案1】:

    几点说明:

    • 2448x3264x(比如 4 字节/像素)约为 30 兆字节。
    • 不要旋转它。如果它在屏幕上显示,您可以使用视图的变换属性。如果它进入一个文件并且旋转是 8 个 exif 方向之一,请写入说明哪条方向向上的元数据。同样,如果它来自一个文件,请使用 Image I/O 并要求 CGImageSourceRef 生成一个定向缩略图,您需要将其放在屏幕上。 (提示使用 kCGImageSourceThumbnailMaxPixelSize 和 kCGImageSourceCreateThumbnailWithTransform。)对于任意角度,您可以使用 CoreImage 过滤器,它将图像旋转并下采样到屏幕所需的大小(在 GPU 上)。同样,您可以使用 vImage 在 CPU 上执行相同的操作(提示 vImageAffineWarpCG_ARGB8888)。 vImage 非常快,它会给你比核心图形更好的重采样。等等......如果它很痛,不要这样做。
    • 在将时间从角度转换为旋转矩阵之前,您应该暂停一下。例如,如果您的角度是 90 度,那么您想要的矩阵正好是 [0 1 -1 0 0 0] 并且您的重采样代码将比您计算的近似结果更满意。旋转矩阵是 [cos(t) sin(t) -sin(t) cos(t) 0 0]。客户可能已经可以直接传入余弦和正弦。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-16
      • 2020-10-03
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2011-04-10
      • 2019-07-29
      相关资源
      最近更新 更多