Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIGraphicsGetImageFromCurrentImageContext() returns nil

Tags:

ios

swift

uiimage

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

enter image description here

like image 660
Javier Flores Font Avatar asked Sep 07 '17 15:09

Javier Flores Font


2 Answers

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.

like image 132
Night Warrier Avatar answered Sep 16 '22 12:09

Night Warrier


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!

like image 42
XiaoMing Avatar answered Sep 17 '22 12:09

XiaoMing