Advertisement
Don_Mag

CIFilter scaling

Feb 28th, 2021
1,470
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.43 KB | None | 0 0
  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.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement