为什么会UIImagePNGRepresentation(UIImage())
退货nil
?
我试图UIImage()
在我的测试代码中创建一个只是为了断言它是正确传递的。
我对两个 UIImage 的比较方法使用UIImagePNGRepresentation()
,但由于某种原因,它返回nil
.
谢谢你。
为什么会UIImagePNGRepresentation(UIImage())
退货nil
?
我试图UIImage()
在我的测试代码中创建一个只是为了断言它是正确传递的。
我对两个 UIImage 的比较方法使用UIImagePNGRepresentation()
,但由于某种原因,它返回nil
.
谢谢你。
UIImagePNGRepresentation()
nil
如果提供的 UIImage 不包含任何数据,将返回。来自UIKit 文档:
返回值
包含 PNG 数据的数据对象,如果生成数据时出现问题,则返回 nil。如果图像没有数据或底层 CGImageRef 包含不受支持的位图格式的数据,此函数可能会返回 nil。
当您UIImage
通过简单地使用来初始化 a 时UIImage()
,它会创建一个UIImage
没有数据的 a。尽管图像不是零,但它仍然没有数据。而且,因为图像没有数据,所以UIImagePNGRepresentation()
只返回nil
.
要解决此问题,您必须使用UIImage
数据。例如:
var imageName: String = "MyImageName.png"
var image = UIImage(named: imageName)
var rep = UIImagePNGRepresentation(image)
imageName
您的应用程序中包含的图像名称在哪里。
要使用UIImagePNGRepresentation(image)
,image
一定不能nil
,而且还必须有数据。
如果你想检查他们是否有任何数据,你可以使用:
if(image == nil || image == UIImage()){
//image is nil, or has no data
}
else{
//image has data
}
图像对象是不可变的,因此您无法在创建后更改它们的属性。这意味着您通常在初始化时指定图像的属性或依赖图像的元数据来提供属性值。
由于您在UIImage
没有提供任何图像数据的情况下创建了该对象,因此您创建的对象作为图像没有任何意义。UIKit 和 Core Graphics 似乎不允许 0x0 图像。
最简单的解决方法是创建一个 1x1 图像:
UIGraphicsBeginImageContext(CGSizeMake(1, 1))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
我遇到了同样的问题,我将 UIImage 转换为 pngData,但有时它返回 nil。我通过创建图像副本来修复它
func getImagePngData(img : UIImage) -> Data {
let pngData = Data()
if let hasData = img.pngData(){
print(hasData)
pngData = hasData
}
else{
UIGraphicsBeginImageContext(img.size)
img.draw(in: CGRect(x: 0.0, y: 0.0, width: img.width,
height: img.height))
let resultImage =
UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
print(resultImage.pngData)
pngData = resultImage.pngData
}
return pngData
}