UIImagePNGRepresentation(UIImage()) returns nil

北慕城南 提交于 2019-12-01 03:28:27

UIImagePNGRepresentation() will return nil if the UIImage provided does not contain any data. From the 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.

When you initialize a UIImage by simply using UIImage(), it creates a UIImage with no data. Although it is not nil, it still has no data, which therefore makes it so UIImagePNGRepresentation() cannot return any data, making it return nil.

To fix this, you would have to use UIImage with data. For example:

var imageName: String = "MyImageName.png"
var image = UIImage(named: imageName)
var rep = UIImagePNGRepresentation(image)

Where imageName is the name of your image, included in your application.

In order to use UIImagePNGRepresentation(image), image must not be nil, and it must have data (UIImage() creates a image that is not nil, but doesn't have any data).

If you want to check if they have any data, you could use:

if(image == nil || image == UIImage()){
  //image is nil, or has no data
}
else{
  //image has data
}

The UIImage documentation says

Image objects are immutable, so you cannot change their properties after creation. This means that you generally specify an image’s properties at initialization time or rely on the image’s metadata to provide the property value.

Since you've created the UIImage without providing any image data, the object you've created has no meaning as an image. UIKit and Core Graphics don't appear to allow 0x0 images.

The simplest fix is to create a 1x1 image instead:

UIGraphicsBeginImageContext(CGSizeMake(1, 1))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!