swift - 使用 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 图像
解决方案
好的,经过一夜好眠,我知道出了什么问题。我在创建 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 中进行图像缩放的合理示例。
推荐阅读
- c++ - Using range-v3 to read comma separated list of numbers
- sql-server - 从日期列表中单独选择日期
- visual-studio-code - 在 VS 代码中读取 cosmosDB 文件时出现问题,原因是:在文件名中
- stored-procedures - 雪花存储过程与独立 sql
- c# - 使用当前 Serilog ILogger 实例将消息格式化为字符串(但不打印)
- cors - 如何从不同的域调用 Vapor?
- r - 建立数据框来预测单变量数据
- rest - REST API 中的并发控制
- java - 处理 Java Keystore 加载错误:java.io.EOFException
- java - 配置 Springfox Swagger 如何排序属性?