I have a table view and in the cell, there is an image and 2 labels. I am using imagePicker
to choose a photo from my camera roll and putting that photo into the cell image. However, when the photo is a portrait mode photo, the image is rotated 90 degrees.
In the code below, posting is an outlet that connects to the imageview
in the table view cell and I initialized a UIImagePickerController
.
class MakePostVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var postImg: UIImageView!
@IBOutlet weak var postTitle: UITextField!
@IBOutlet weak var postDescrip: UITextField!
var imgPicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
postImg.layer.cornerRadius = 30
postImg.clipsToBounds = true
imgPicker = UIImagePickerController()
imgPicker.delegate = self
}
Here is my function for didFinishPickingImage
:
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imgPicker.dismissViewControllerAnimated(true, completion: nil)
postImg.image = image
}
I've looked at similar posts here on SO but the solutions don't seem to work.
Any suggestions?
Thanks
Sunil Sharma's solution worked for me. Here is translated version to Swift 5
extension UIImage {
var fixedOrientation: UIImage {
guard imageOrientation != .up else { return self }
var transform: CGAffineTransform = .identity
switch imageOrientation {
case .down, .downMirrored:
transform = transform
.translatedBy(x: size.width, y: size.height).rotated(by: .pi)
case .left, .leftMirrored:
transform = transform
.translatedBy(x: size.width, y: 0).rotated(by: .pi)
case .right, .rightMirrored:
transform = transform
.translatedBy(x: 0, y: size.height).rotated(by: -.pi/2)
case .upMirrored:
transform = transform
.translatedBy(x: size.width, y: 0).scaledBy(x: -1, y: 1)
default:
break
}
guard
let cgImage = cgImage,
let colorSpace = cgImage.colorSpace,
let context = CGContext(
data: nil, width: Int(size.width), height: Int(size.height),
bitsPerComponent: cgImage.bitsPerComponent, bytesPerRow: 0,
space: colorSpace, bitmapInfo: cgImage.bitmapInfo.rawValue
)
else { return self }
context.concatenate(transform)
var rect: CGRect
switch imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
rect = CGRect(x: 0, y: 0, width: size.height, height: size.width)
default:
rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
}
context.draw(cgImage, in: rect)
return context.makeImage().map { UIImage(cgImage: $0) } ?? self
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With