0

i have problem i try use filter at some images which have extension 3000x2000 , when i do it RAM upper and app have fatal error the "didReceiveMemoryWarning".

 func setFilters(images: [UIImage]) -> [UIImage] {
    let filter = CIFilter(name: "CIColorControls")!
    filter.setValue(2.0, forKey: kCIInputContrastKey)

    let context = CIContext(options: nil)

    var result = [UIImage]()

    for img in images {
        let newImage = autoreleasepool(invoking: { () -> UIImage in
            filter.setValue(CIImage(image: img)!, forKey: kCIInputImageKey)

            let ciImage = filter.outputImage!
            let cgImage = context.createCGImage(ciImage, from: ciImage.extent)


            return UIImage(cgImage: cgImage!, scale: img.scale, orientation: img.imageOrientation)
        })

        result.append(newImage)
    }

    return result
}

1 Answers1

2

It's not a memory leak; it's that you are in fact using too much memory. And it's not the use of CIFilter that's causing the problem; it's the fact that you are trying to keep all of these huge UIImage objects in memory in a single array:

var result = [UIImage]()
// ...
result.append(newImage)

Don't do that.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Then how to store images after filter , i did 10 photo's and tried do filter for them and save to phone. – Алексей Моисеев Dec 26 '16 at 16:40
  • You can save them, but you need to save each one _immediately_, not wait until you've filtered 10 of them. You don't have the memory for that. Similarly you can't take 10 photos and keep them all in memory. Save each one to disk initially. Load only _one_ photo for processing, process it, save the processed photo, and release both photos. Repeat. Simple. – matt Dec 26 '16 at 16:44
  • If i will comment line with "result.append(newImage)" the program will crash bcs of the didReceiveMemoryWarning. – Алексей Моисеев Dec 26 '16 at 16:49
  • Because you are still starting with `images: [UIImage]`. You do not have room for an array of images. – matt Dec 26 '16 at 16:54
  • Also this line is a big waste of memory: `UIImage(cgImage: cgImage!, scale: img.scale, orientation: img.imageOrientation)` You have the CGImage already. That's the end. That is your photo data. Save _that_ into the photo library. – matt Dec 26 '16 at 17:10