UIimage Detect Landscape Image with Swift

233 Views Asked by At

I want to read a photo from Library

in this function

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

now I want to know is that landscape photo or not I try to tie this code

if(pickedImage?.size.width > pickedImage?.size.height)

But I received this error Binary operator '>' cannot be applied to two 'CGFloat?' operands how can I resolve this Problem

4

There are 4 best solutions below

0
Shehata Gamal On BEST ANSWER

Try this

 if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage

   { 
      if pickedImage.size.width > pickedImage.size.height 
      {
         /// landscape mode
      }

   }

}
0
pacification On

The problem here that you try to work with Optional values, instead of unwrapped. To unwrap value you can use guard:

guard let pickedImage = pickedImage else { 
    // false logic here
    return 
}

if pickedImage.size.height > pickedImage.size.height {

} else {

}

By the way, are you sure that you want to compare pickedImage's height to itself? Looks weird.

5
Miloo On

I find the solution with this code ? -> !

if(pickedImage!.size.width > pickedImage!.size.height)
0
kiwisip On

Another possible solution could be to use switch pattern matching:

switch image?.size {
case .some(let size) where size.height > size.width:
  // do something
default:
  break
}