title: Resizing Images using Core Graphics / Quartz 2D in Swift
body: <p>I'd like to use Core Graphics to resize some images because I have an image heavy app. I'm using this method below:</p>
  
  <pre><code>func createContext(image: UIImage) -&gt; UIImage? {
      let cgImage = image.CGImage
  
      let width = Int(image.size.width)
      let height = Int(image.size.height)
      let bitsPerComponent = CGImageGetBitsPerComponent(cgImage)
      let bytesPerRow = CGImageGetBytesPerRow(cgImage)
      let colorSpace = CGImageGetColorSpace(cgImage)
      let bitmapInfo = CGImageGetBitmapInfo(cgImage)
  
      let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo.rawValue)
  
      CGContextSetInterpolationQuality(context, .High)
  
      CGContextDrawImage(context, CGRect(origin: CGPointZero, size: CGSize(width: image.size.width, height: image.size.height)), cgImage)
  
      let scaledImage = CGBitmapContextCreateImage(context).flatMap { UIImage(CGImage: $0) }
  
      return scaledImage
  }
  </code></pre>
  
  <p>and the returned image looks great on landscape images, but for portrait images, it looks like this:</p>
  
  <p><img src="https://i.imgur.com/IpApAFf.jpg" alt="wrong"></p>
  
  <p>I can change the code to bring in UIKit elements:</p>
  
  <pre><code>func createContext(image: UIImage) -&gt; UIImage? {
      let cgImage = image.CGImage
      let rect = CGRectMake(0, 0, image.size.width, image.size.height)
  
      let size = image.size
      let scale: CGFloat = 0.0
      let width = CGImageGetWidth(cgImage) / 2
      let height = CGImageGetHeight(cgImage) / 2
      let bitsPerComponent = CGImageGetBitsPerComponent(cgImage)
      let bytesPerRow = CGImageGetBytesPerRow(cgImage)
      let colorSpace = CGImageGetColorSpace(cgImage)
      let bitmapInfo = CGImageGetBitmapInfo(cgImage)
  
      UIGraphicsBeginImageContextWithOptions(size, false, scale)
      image.drawInRect(CGRect(origin: CGPointZero, size: size))
  
      let context = CGBitmapContextCreate(nil, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo.rawValue)
  
      CGContextSetInterpolationQuality(context, .High)
      let myGeneratedImage = CGBitmapContextCreateImage(context)
  
      CGContextDrawImage(context, rect, myGeneratedImage)
  
      let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
  
      return scaledImage
  }
  </code></pre>
  
  <p>and it looks like this, which is what I want.</p>
  
  <p><img src="https://i.imgur.com/9N0Np3Y.jpg" alt="right"></p>
  
  <p>However, I want to do my best to avoid bringing in UIKit and keep the code lower level by using only Core Graphics, can someone point out what I'm doing incorrectly? Feel free to reply in objC or Swift code if you're able to see my errors.</p>