title: Swift resize Image
body: <p>I found the below code to resize the image, but I get error while using it. It says </p>
  
  <blockquote>
    <p>fatal error: unexpectedly found nil while unwrapping an Optional value</p>
  </blockquote>
  
  <p>I couldn't find the reason of the error.</p>
  
  <p>ResizeImage func :</p>
  
  <pre><code>func ResizeImage(image: UIImage, targetSize: CGSize) -&gt; UIImage {
          let size = image.size
          let widthRatio  = targetSize.width  / image.size.width
          let heightRatio = targetSize.height / image.size.height
  
          // Figure out what our orientation is, and use that to form the rectangle
          var newSize: CGSize
          if(widthRatio &gt; heightRatio) {
              newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
          } else {
              newSize = CGSizeMake(size.width * widthRatio,  size.height * widthRatio)
          }
  
          // This is the rect that we've calculated out and this is what is actually used below
          let rect = CGRectMake(0, 0, newSize.width, newSize.height)
  
          // Actually do the resizing to the rect using the ImageContext stuff
          UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
          image.drawInRect(rect)
          let newImage = UIGraphicsGetImageFromCurrentImageContext()
          UIGraphicsEndImageContext()
          return newImage
      }
  </code></pre>
  
  <p>My ImagePickerController:</p>
  
  <pre><code>func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject])
      {
  
          let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
  
          if flag == 1 {
              //self.ResizeImage(UIImage(named: "\(pickedImage)")!, targetSize: CGSizeMake(200.0, 200.0))
              leftImage.image = self.ResizeImage(UIImage(named: "pickedImage")!, targetSize: CGSizeMake(750.0, 750.0)) //pickedImage
              let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
              let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
              photo1 = base64String
  
          }else if flag == 2 {
              rightImage.image = self.ResizeImage(UIImage(named: "\(pickedImage)")!, targetSize: CGSizeMake(750.0, 750.0)) //pickedImage
              let imageData = UIImageJPEGRepresentation(pickedImage!, 0.5)
              let base64String = imageData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
              photo2 = base64String
          }
  
          dismissViewControllerAnimated(true, completion: nil)
  
  
  
      }
  </code></pre>