gpt4 book ai didi

swift - UIImagePNGRepresentation(UIImage()) 返回 nil

转载 作者:IT王子 更新时间:2023-10-29 05:41:22 25 4
gpt4 key购买 nike

为什么 UIImagePNGRepresentation(UIImage()) 返回 nil

我试图在我的测试代码中创建一个 UIImage() 只是为了断言它已正确传递。

我对两个 UIImage 的比较方法使用了 UIImagePNGRepresentation(),但由于某种原因,它返回了 nil

谢谢。

最佳答案

UIImagePNGRepresentation()如果提供的 UIImage 不包含任何数据,将返回 nil。来自UIKit Documentation :

Return Value

A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.

当你初始化一个 UIImage通过简单地使用 UIImage(),它创建一个没有数据的 UIImage。虽然图像不是零,但它仍然没有数据。而且,因为图像没有数据,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
}

关于swift - UIImagePNGRepresentation(UIImage()) 返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28846705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com