使用系统相机拍照后保存到本机

[Swift] 纯文本查看 复制代码
let data:NSData = UIImagePNGRepresentation(image)!
data.writeToFile(filePath, atomically: true)


UIImage带有一个imageOrientation属性,在UIImageView中会正常显示,但保存后的图片没有这个属性,如果使用另外三个方向拍摄的照片,再显示时就会出现方向错误的问题。



通过判断拍摄时的方向属性,保存时将图片旋转为正确的方向,即可修复:

[Swift] 纯文本查看 复制代码
func fixImageOrientation(src:UIImage) -> UIImage {

//旋转弧度
var radians:Double

//旋转后的区域
var drawRect:CGRect

//旋转后的尺寸
var rotatedSize = CGSizeMake(src.size.width, src.size.height)

//不同拍摄方向的处理
switch src.imageOrientation{
	case UIImageOrientation.Down:
		radians = ASMathUtils.degreesToRadians(180)
		drawRect = CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.width, src.size.height)
	case UIImageOrientation.Up:
		return src
	case UIImageOrientation.Left:
		radians = ASMathUtils.degreesToRadians(-90)
		drawRect = CGRectMake(-src.size.height / 2, -src.size.width / 2, src.size.height, src.size.width)
	case UIImageOrientation.Right:
		radians = ASMathUtils.degreesToRadians(90)
		drawRect = CGRectMake(-src.size.width / 2, -src.size.height / 2, src.size.height, src.size.width)
		rotatedSize.width = src.size.height
		rotatedSize.height = src.size.width
	default:
		return src
}

//重绘出旋转后的图像
UIGraphicsBeginImageContextWithOptions(src.size, false, 1.0 )
let bitmap = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2)
CGContextRotateCTM(bitmap, CGFloat(radians))
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, drawRect,src.CGImage)

let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}