[英]UIGraphicsImageRenderer: pngData for grayscale image
I have enjoyed using the newer APIs from UIGraphicsImageRenderer
introduced since iOS 10, but now I'm wondering if it's possible at all to get a grayscale Data
from its pngData
method. 我很高兴使用自iOS 10以来引入的
UIGraphicsImageRenderer
的新API,但现在我想知道是否可以从其pngData
方法获取灰度Data
。
Say I have an input image called "mask.png", a grayscale image. 假设我有一个名为“mask.png”的输入图像,一个灰度图像。 I have verified that it loads up as grayscale by looking at
UIImage
's underlying colorspace. 我已经通过查看
UIImage
的底层色彩空间来验证它是否加载为灰度。 The older API UIImagePNGRepresentation
seems to be able to detect the colorspace and encode its returned Data
properly. 较旧的API
UIImagePNGRepresentation
似乎能够检测颜色空间并正确编码其返回的Data
。 However, the pngData
function introduced since iOS 10 seems to convert my Data
to RGB colorspace. 但是,自iOS 10以来引入的
pngData
函数似乎将我的Data
转换为RGB色彩空间。
extension UIImage {
public func pngData_olderAPI() -> Data? {
return UIImagePNGRepresentation(self)
}
public func pngData() -> Data {
let renderedSize = CGSize(width: size.width, height: size.height)
let renderer = UIGraphicsImageRenderer(size: renderedSize, format: UIGraphicsImageRendererFormat())
return renderer.pngData { (rendererContext) in
let rect = CGRect(x: 0, y: 0, width: renderedSize.width, height: renderedSize.height)
self.draw(in: rect)
}
}
}
let mask = UIImage(named: "mask.png")
print(mask?.cgImage?.colorSpace.debugDescription)
let data = mask?.pngData_olderAPI()
let unwrappedMask = UIImage(data: data!)
print(unwrappedMask?.cgImage?.colorSpace.debugDescription)
let data2 = mask?.pngData()
let unwrappedMask2 = UIImage(data: data2!)
print(unwrappedMask2?.cgImage?.colorSpace.debugDescription)
Here's the (simplified) output: 这是(简化)输出:
...kCGColorSpaceModelMonochrome; Dot Gain 20%))")
...kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Dot Gain 20%))")
...kCGColorSpaceICCBased; kCGColorSpaceModelRGB; sRGB IEC61966-2.1))")
I don't see how I can set the colorspace in the newer API. 我没有看到如何在较新的API中设置色彩空间。 Is it possible to save a grayscale image with the new API?
是否可以使用新API保存灰度图像?
As of iOS 12, UIGraphicsImageRender
will automatically select the right color space based on the drawing performed. 从iOS 12开始,
UIGraphicsImageRender
将根据执行的绘图自动选择正确的颜色空间。 In my case, it automatically created the image with the grayscale color space. 在我的例子中,它自动创建具有灰度色彩空间的图像。
<CGColorSpace 0x280d869a0> (kCGColorSpaceICCBased; kCGColorSpaceModelMonochrome; Generic Gray Gamma 2.2 Profile)
This was explained in the iOS Memory Deep Dive session at WWDC 2018. 这在WWDC 2018的iOS Memory Deep Dive会话中进行了解释。
There isn't a way to manually specify a color space with this API. 没有办法使用此API手动指定颜色空间。 Related to this however, you can set the
preferredRange
on UIGraphicsImageRendererFormat
, but there's not an option for preferring monochrome. 但是,与此相关,您可以在
UIGraphicsImageRendererFormat
上设置preferredRange
,但是没有选择单色的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.