I have this extension of UIImage:
extension UIImage {
func resizeImage(newWidth: CGFloat, newHeight: CGFloat? = nil) -> UIImage {
let scale = newWidth / self.size.width
let finalHeight = (newHeight == nil) ? self.size.height * scale : newHeight!
UIGraphicsBeginImageContextWithOptions(CGSize(width:newWidth, height: finalHeight), false, self.scale)
self.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: finalHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Why is UIGraphicsGetImageFromCurrentImageContext returning nil? Does it have something to do with the image size?
(lldb) po self.size ▿ (3024.0, 4032.0) - width : 3024.0 - height : 4032.0
Looks like UIGraphicsBeginImageContextWithOptions is implemented so that it tries to allocate a consecutive region of memory for image buffer. The region is really big and can be as big as 50MB. What happens is that "malloc" call returns null, and the call to UIGraphicsBeginImageContextWithOptions fails silently. The reasons for malloc failure could be different from memory shortage to memory fragmentation, this is the reason why the reproduction of this problem is not consistent.
I met this problem too. The first time UIGraphicsGetImageFromCurrentImageContext()
return nil, but the same code, on the second time, can get the return data. At last I found, if the view's subview's size is zero, this problem will happen. So I suggest you to check and remove the view's subviews which size is zero. I hope that work for you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With