在Swift 3.0及更高版本中上传到服务器之前,图像方向是否正确?

您可以从应用中拍摄一张照片,然后将其以纵向显示在图像视图中,但是每当将此图像上载到服务器时,该图像的原始方向都没有。 因此,来自服务器的图像将原始人像图像旋转90度。

因此,您必须正确旋转,然后才能在服务器上上传原始图像。

在此处创建功能,以便在Swift 3.0及更高版本中定位图像。

  func imageOrientation(_ srcImage:UIImage)-> UIImage { 
如果srcImage.imageOrientation == UIImageOrientation.up {
返回srcImage
}
var转换:CGAffineTransform = CGAffineTransform.identity
切换srcImage.imageOrientation {
case UIImageOrientation.down,UIImageOrientation.downMirrored:
transform = transform.translatedBy(x:srcImage.size.width,y:srcImage.size.height)
转换= transform.rotated(作者:CGFloat(M_PI))//使用Swift 4.0时用Double.pi替换M_PI
打破
case UIImageOrientation.left,UIImageOrientation.leftMirrored:
transform = transform.translatedBy(x:srcImage.size.width,y:0)
当使用Swift 4.0时,transform = transform.rotated(作者:CGFloat(M_PI_2))//用Double.pi / 2替换M_PI_2
打破
case UIImageOrientation.right,UIImageOrientation.rightMirrored:
transform = transform.translatedBy(x:0,y:srcImage.size.height)
当使用Swift 4.0时,transform = transform.rotated(作者:CGFloat(-M_PI_2))//用Double.pi / 2替换M_PI_2
打破
案例UIImageOrientation.up,UIImageOrientation.upMirrored:
打破
}切换srcImage.imageOrientation {
UIImageOrientation.upMirrored,UIImageOrientation.downMirrored的情况:
transform.translatedBy(x:srcImage.size.width,y:0)
transform.scaledBy(x:-1,y:1)
打破
case UIImageOrientation.leftMirrored,UIImageOrientation.rightMirrored:
transform.translatedBy(x:srcImage.size.height,y:0)
transform.scaledBy(x:-1,y:1)
case UIImageOrientation.up,UIImageOrientation.down,UIImageOrientation.left,UIImageOrientation.right:
打破
} let ctx:CGContext = CGContext(数据:无,宽度:Int(srcImage.size.width),高度:Int(srcImage.size.height),bitsPerComponent:(srcImage.cgImage)!. bitsPerComponent,bytesPerRow:0,空格:(srcImage.cgImage)!. colorSpace !, bitmapInfo:CGImageAlphaInfo.premultipliedLast.rawValue)!ctx.concatenate(transform)switch srcImage.imageOrientation {
case UIImageOrientation.left,UIImageOrientation.leftMirrored,UIImageOrientation.right,UIImageOrientation.rightMirrored:
ctx.draw(srcImage.cgImage !,在:CGRect(x:0,y:0,宽度:srcImage.size.height,高度:srcImage.size.width))
打破
默认:
ctx.draw(srcImage.cgImage !,在:CGRect(x:0,y:0,宽度:srcImage.size.width,高度:srcImage.size.height))
打破
}让cgimg:CGImage = ctx.makeImage()!
让img:UIImage = UIImage(cgImage:cgimg)返回img
}

如何使用 :

在服务器上上传图像之前,您必须调整方向。 当您将图像放置在方位图像上时。

  func imagePickerController(__ picker:UIImagePickerController,didFinishPickingMediaWithInfo信息:[String:任何]){ 
var image = info [UIImagePickerControllerOriginalImage]如! UIImage
图片= self.imageOrientation(图片)
}