首页 > 解决方案 > 使用 Core Image 缩放图像是裁剪而不是缩放

问题描述

我有一个应该使用核心图像过滤器缩放图像的功能。它接受一个 NSImage 和一个维数作为参数并返回一个缩放的 NSImage。我一直在使用:Processing an Image Using Built-in Filters as a reference。该代码似乎正在裁剪图像而不是调整其大小。我发誓我曾经让它工作过,所以我哪里出错了?

func imageCIScale(_ image: NSImage, dimension: CGFloat) -> NSImage? {
    guard let data = image.tiffRepresentation,
        let scaleFilter = CIFilter(name: "CILanczosScaleTransform"),
        let ciImage = CIImage(data: data)
    else {
        print("Failure! Abject failure! Couldn't even get started")
        return nil
    }

    let scaleFactor = dimension / image.size.height

    scaleFilter.setValue(ciImage, forKey: kCIInputImageKey)
    scaleFilter.setValue(scaleFactor, forKey: kCIInputScaleKey)
    scaleFilter.setValue(1.0, forKey: kCIInputAspectRatioKey)
    let outputImage = scaleFilter.outputImage

    let context = CIContext()
    guard let scaledImage = context.createCGImage(ciImage, from: outputImage!.extent) else {
        print("Failed to create CGImage")
        return nil
    }

    return NSImage(cgImage: scaledImage, size: NSZeroSize)
}

该函数将被称为:

let myScaledNSImage = imageCIScale(myOriginalNSImage, dimension: 32.0)

并应产生 32 x 32 图像

标签: swiftcocoacore-imageswift4.2

解决方案


好的,经过一夜好眠,我知道出了什么问题。我在创建 CG 图像时使用了错误的图像源

let scaledImage = context.createCGImage(ciImage, from: outputImage!.extent)

应该

let scaledImage = context.createCGImage(outputImage!, from: outputImage!.extent)

或者更像

let context = CIContext()
guard let outputImage = scaleFilter.outputImage,
      let scaledImage = context.createCGImage(outputImage, from: outputImage.extent)
else {
    print("Failed to create CGImage")
    return nil
}

我会留下这个问题,因为一旦更正,我认为这是在 Mac OS 上下文中在 Swift 4.2 中进行图像缩放的合理示例。


推荐阅读