像素化 UIImage returns 具有不同大小的 UIImage

Pixellating a UIImage returns UIImage with a different size

我正在使用扩展程序对我的图像进行像素化,如下所示:

func pixellated(scale: Int = 8) -> UIImage? {
    guard let ciImage = CIImage(image: self), let filter = CIFilter(name: "CIPixellate") else { return nil }
    filter.setValue(ciImage, forKey: kCIInputImageKey)
    filter.setValue(scale, forKey: kCIInputScaleKey)

    guard let output = filter.outputImage else { return nil }

    return UIImage(ciImage: output)
}

问题是这里用self表示的图像与我用UIImage(ciImage: output)创建的图像大小不一样。

例如,使用该代码:

print("image.size BEFORE : \(image.size)")
if let imagePixellated = image.pixellated(scale: 48) {
    image = imagePixellated
    print("image.size AFTER : \(image.size)")
}

将打印:

image.size BEFORE : (400.0, 298.0)
image.size AFTER : (848.0, 644.0)

大小不一样,比例不一样

知道为什么吗?

编辑:

我在扩展中添加了一些打印如下:

func pixellated(scale: Int = 8) -> UIImage? {
    guard let ciImage = CIImage(image: self), let filter = CIFilter(name: "CIPixellate") else { return nil }

    print("UIIMAGE : \(self.size)")
    print("ciImage.extent.size : \(ciImage.extent.size)")

    filter.setValue(ciImage, forKey: kCIInputImageKey)
    filter.setValue(scale, forKey: kCIInputScaleKey)

    guard let output = filter.outputImage else { return nil }

    print("output : \(output.extent.size)")

    return UIImage(ciImage: output)
}

这里是输出:

UIIMAGE : (250.0, 166.5)
ciImage.extent.size : (500.0, 333.0)
output : (548.0, 381.0)

你有两个问题:

  1. self.size 以点为单位。 self 的像素大小实际上是 self.size 乘以 self.scale
  2. CIPixellate 滤镜更改其图像的边界。

要解决问题一,只需将返回的 UIImagescale 属性 设置为与 self.scale:

相同
return UIImage(ciImage: output, scale: self.scale, orientation: imageOrientation)

但是你会发现这还是不太对。那是因为问题二。对于问题二,最简单的解决方案是裁剪输出 CIImage:

// Must use self.scale, to disambiguate from the scale parameter
let floatScale = CGFloat(self.scale)
let pixelSize = CGSize(width: size.width * floatScale, height: size.height * floatScale)
let cropRect = CGRect(origin: CGPoint.zero, size: pixelSize)
guard let output = filter.outputImage?.cropping(to: cropRect) else { return nil }

这将为您提供所需尺寸的图像。

现在,您的下一个问题可能是,"why is there a thin, dark border around my pixellated images?"好问题!但是问一个新问题。