Don_Mag

CIFilter scaling

Feb 28th, 2021
550
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class ViewController: UIViewController {
  2.    
  3.     override func viewDidLoad() {
  4.         super.viewDidLoad()
  5.        
  6.         guard let img = UIImage(named: "sampleImage") else {
  7.             fatalError("Could not load image!!!!")
  8.         }
  9.  
  10.         /// goal is to scale twice the PIXEL size
  11.        
  12.         if let scaledImage = imageCIScale(img, dimension: 2.0, outputScale: 1.0) {
  13.  
  14.             print("original image size:", img.size)
  15.             print("scaled x 2.0 with 1.0 scale:", scaledImage.size)
  16.            
  17.         }
  18.        
  19.         if let scaledImage = imageCIScale(img, dimension: 2.0, outputScale: UIScreen.main.scale) {
  20.            
  21.             print("original image size:", img.size)
  22.             print("scaled x 2.0 with Screen scale:", scaledImage.size)
  23.            
  24.         }
  25.  
  26.     }
  27.    
  28.     func imageCIScale(_ image: UIImage, dimension: CGFloat, outputScale: CGFloat) -> UIImage? {
  29.        
  30.         guard let ciImage = CIImage(image: image) else {
  31.             print("no ciImage")
  32.             return nil
  33.         }
  34.         guard let scaleFilter = CIFilter(name: "CILanczosScaleTransform") else {
  35.             print("no filter")
  36.             return nil
  37.         }
  38.        
  39.         scaleFilter.setValue(ciImage, forKey: kCIInputImageKey)
  40.        
  41.         scaleFilter.setValue(ciImage, forKey: kCIInputImageKey)
  42.         scaleFilter.setValue(dimension, forKey: kCIInputScaleKey)
  43.         scaleFilter.setValue(1.0, forKey: kCIInputAspectRatioKey)
  44.        
  45.         guard let outputImage = scaleFilter.outputImage else { return nil }
  46.        
  47.         let uiImage = UIImage(ciImage: outputImage, scale: outputScale, orientation: image.imageOrientation)
  48.        
  49.         return uiImage
  50.        
  51.     }
  52.  
  53. }
  54.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×