import CoreGraphics extension CGImage { func resize(size:CGSize) -> CGImage? { let width: Int = Int(size.width) let height: Int = Int(size.height) let bytesPerPixel = self.bitsPerPixel / self.bitsPerComponent let destBytesPerRow = width * bytesPerPixel guard let colorSpace = self.colorSpace else { return nil } guard let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: self.bitsPerComponent, bytesPerRow: destBytesPerRow, space: colorSpace, bitmapInfo: self.alphaInfo.rawValue) else { return nil } context.interpolationQuality = .none context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) return context.makeImage() } }