我目前正在使用CGContextDrawImage
旋转图像,但每次调用时都会出现巨大的内存消耗。新设备可以处理它,但像iPhone 4s这样RAM较低的设备无法处理。该图像是用户以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 的低级代码来实现这一点,就像上面的代码所做的那样?
我还想避免在上传之前缩小图像。
是否有任何减少旋转图像影响的方法,例如分别旋转它的不同部分,或者我必须找到另一种替代方法?
AVCaptureSessionPresetHigh
下拍摄的照片。 - Jojodmo