iOS UIImagePickerController result image orientation after upload

后端 未结 20 1944
长发绾君心
长发绾君心 2020-11-22 00:44

I am testing my iPhone application on an iOS 3.1.3 iPhone. I am selecting/capturing an image using a UIImagePickerController:

UIImagePickerCont         


        
20条回答
  •  梦如初夏
    2020-11-22 01:19

    Here is a Swift version of the answer by @an0:

    func normalizedImage() -> UIImage {
    
      if (self.imageOrientation == UIImageOrientation.Up) { 
          return self;
      }
    
      UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale);
      let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
      self.drawInRect(rect)
    
      let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext();
      return normalizedImage;
    }
    

    Also in a more general function:

    func fixOrientation(img:UIImage) -> UIImage {
    
      if (img.imageOrientation == UIImageOrientation.Up) { 
          return img;
      }
    
      UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale);
      let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
      img.drawInRect(rect)
    
      let normalizedImage : UIImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext();
      return normalizedImage;
    
    }
    

    Swift 3 version:

    func fixOrientation(img: UIImage) -> UIImage {
        if (img.imageOrientation == .up) {
            return img
        }
    
        UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
        let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
        img.draw(in: rect)
    
        let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
    
        return normalizedImage
    }
    

提交回复
热议问题