UIImagePNGRview (UIImage ()) returns zero

Why UIImagePNGRepresentation(UIImage()) return nil ?

I am trying to create UIImage() in my test code to claim that it was passed correctly.

My comparison method for two UIImage uses UIImagePNGRepresentation() , but for some reason it returns nil .

Thanks.

+6
source share
2 answers

UIImagePNGRepresentation() will return nil if the provided UIImage does not contain any data. From the UIKit Documentation :

Return value

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

When you initialize UIImage simply using UIImage() , it creates a UIImage without data. Although this is not nil , it still has no data, so it UIImagePNGRepresentation() cannot return data, forcing it to return nil .

To fix this, you will need to use UIImage with the data. For instance:

 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.

To use UIImagePNGRepresentation(image) , image must not be nil , and it must have data ( UIImage() creates an image that is not nil , but does not contain any data).

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

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

UIImage documentation says

Image objects are immutable, so you cannot change their properties after creation. This means that you usually specify image properties during initialization or rely on image metadata to provide a property value.

Since you created UIImage without providing any image data, the created object has no meaning in the quality of the image. UIKit and Core Graphics do not display 0x0 images.

The simplest solution is to create a 1x1 image instead of:

 UIGraphicsBeginImageContext(CGSizeMake(1, 1)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() 
+4
source

Source: https://habr.com/ru/post/983296/


All Articles