使用CILanczosScaleTransform核心图像过滤器调整图像大小

时间:2015-03-12 11:28:34

标签: ios swift core-image

我正在尝试使用CILanczosScaleTransform核心图像过滤器来调整图像大小,但我遇到了问题。这是我的代码:

var imageView: UIImageView = UIImageView()
var image: UIImage?
imageView.frame = CGFrameMake(10,10,200,300)
dispatch_async(dispatch_get_main_queue(), {
    let nsurl = NSURL(string:"http://...")
    var err: NSError?
    var getImageData = NSData(contentsOfURL: nsurl!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    if let imageData = getImageData {
        if let receivedImage = UIImage(data: imageData){
            image = receivedImage
/*
  so far all this code works fine, if I set imageView.image = image 
  the image displays with no problems...

  ...the problems are in this bit of code:
                                                    */
            let context = CIContext(options:nil)
            var ciimg = CIImage(image: image)
            var filter = CIFilter(name: "CILanczosScaleTransform")
            filter.setValue(image, forKey: kCIInputImageKey)
            filter.setValue(0.667, forKey: kCIInputScaleKey)
            let result: CIImage = filter.outputImage

            let extent = result.extent() // <-- specifically this line

            let newImage: UIImage? = UIImage(CIImage: result)
            imageView.image = newImage
        }
    }
})

当执行到达行let extent = result.extent()时,我收到以下运行时错误:

-[UIImage extent]: unrecognized selector sent to instance 0x7a457790
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIImage extent]: unrecognized selector sent to instance 0x7a457790'

我将我在Apple's Core Image Programming Guide找到的代码从Objective C转换为Swift,感觉我可能误译了它。

有人可以把我弄好吗?

1 个答案:

答案 0 :(得分:4)

好的,这是我的错。这一行:filter.setValue(image, forKey: kCIInputImageKey)正在使用UIImage中的image并在过滤器中使用它,而应该使用CIImage中的ciimg

所以完整的代码应该是:

var imageView: UIImageView = UIImageView()
var image: UIImage?
imageView.frame = CGFrameMake(10,10,200,300)
dispatch_async(dispatch_get_main_queue(), {
    let nsurl = NSURL(string:"http://...")
    var err: NSError?
    var getImageData = NSData(contentsOfURL: nsurl!, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    if let imageData = getImageData {
        if let receivedImage = UIImage(data: imageData){
            image = receivedImage
            let context = CIContext(options:nil)
            var ciimg = CIImage(image: image)
            var filter = CIFilter(name: "CILanczosScaleTransform")
            filter.setValue(ciimg, forKey: kCIInputImageKey)
            filter.setValue(0.667, forKey: kCIInputScaleKey)
            let result: CIImage = filter.outputImage
            let extent = result.extent()
            let newImage: UIImage? = UIImage(CIImage: result)
            imageView.image = newImage
        }
    }
})