cuốn sách gpt4 ai đã làm

ios - 像素化 UIImage 返回具有不同大小的 UIImage

In lại Tác giả: Walker 123 更新时间:2023-11-28 15:37:55 28 4
mua khóa gpt4 Nike

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

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)

大小不一样,比例也不一样。

知道为什么吗?

biên tập:

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

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)

câu trả lời hay nhất

你有两个问题:

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

要解决问题一,您只需将返回的 UIImage của tỉ lệ 属性设置为与 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 }

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

现在,您的下一个问题可能是,“为什么我的像素化图像周围有一条又细又黑的边框?”好问题!但是为此提出一个新问题。

关于ios - 像素化 UIImage 返回具有不同大小的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104448/

28 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress