我目前正在使用CGContextDrawImage
旋转图像,但无论何时调用它都会有一个巨大的内存峰值。较新的设备可以处理它,但是具有较低内存的设备(例如iPhone 4s)则不能。该图像是用户在AVCaptureSessionPresetHigh
我目前正在使用此扩展程序将图片旋转到UIImage
func rotate(orientation: UIImageOrientation) -> UIImage{
if(orientation == UIImageOrientation.Up){return self}
var transform: CGAffineTransform = CGAffineTransformIdentity
if(orientation == UIImageOrientation.Down || orientation == UIImageOrientation.DownMirrored){
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
}
else if(orientation == UIImageOrientation.Left || orientation == UIImageOrientation.LeftMirrored){
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
}
else if(orientation == UIImageOrientation.Right || orientation == UIImageOrientation.RightMirrored){
transform = CGAffineTransformTranslate(transform, 0, self.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2))
}
if(orientation == UIImageOrientation.UpMirrored || orientation == UIImageOrientation.DownMirrored){
transform = CGAffineTransformTranslate(transform, self.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
}
else if(orientation == UIImageOrientation.LeftMirrored || orientation == UIImageOrientation.RightMirrored){
transform = CGAffineTransformTranslate(transform, self.size.height, 0)
transform = CGAffineTransformScale(transform, -1, 1);
}
let ref: CGContextRef = CGBitmapContextCreate(nil, Int(self.size.width), Int(self.size.height), CGImageGetBitsPerComponent(self.CGImage), 0, CGImageGetColorSpace(self.CGImage), CGImageGetBitmapInfo(self.CGImage))
CGContextConcatCTM(ref, transform)
if(orientation == UIImageOrientation.Left || orientation == UIImageOrientation.LeftMirrored || orientation == UIImageOrientation.Right || orientation == UIImageOrientation.RightMirrored){
CGContextDrawImage(ref, CGRectMake(0, 0, self.size.height, self.size.width), self.CGImage)
}
else{
CGContextDrawImage(ref, CGRectMake(0, 0, self.size.width, self.size.height), self.CGImage)
}
let cgImg: CGImageRef = CGBitmapContextCreateImage(ref)
let rotated: UIImage = UIImage(CGImage: cgImg)!
return rotated
}
此代码适用于iPhone 5和6等设备,但由于内存不足,几乎总会导致iPhone 4s崩溃。
我知道我可以使用指定方向的EXIF数据上传图像,但我觉得只需在上传之前旋转图像就可以防止出现进一步的问题。
iOS如何使用EXIF数据旋转图像以进行显示?例如,虽然使用
UIImage(image.CGImage, scale: 1.0, orientation: UIImageOrientation.Right)
更改EXIF数据,图像仍然以正确的方向显示在屏幕上,对内存的影响要小得多。是否有一些真正的低级代码可以通过像上面的代码一样使用GPU来实现这个目的呢?
我还想在上传之前避免缩小图像。
有什么方法可以减少旋转图像的影响,例如将其旋转成碎片,还是我必须找到替代品?