ColorKit icon indicating copy to clipboard operation
ColorKit copied to clipboard

dominantColors function crash for particular image

Open NatashaLavrinenko opened this issue 2 years ago • 1 comments

Hey! Found a bug for the following function:

extension UIImage {
 func getDominantColors(with minCount: Int = 0) -> [UIColor]? {
        var resultColors: [UIColor]?
        // Try With PNG Data
        if let pngData = pngData(),
           let pngImage = UIImage(data: pngData),
           let colors = try? pngImage.dominantColors(with: .best, algorithm: .iterative) {
            if colors.count >= minCount {
                return colors
            } else {
                resultColors = colors
            }
        }
        // Try With JPEG Data
        if let jpegData = jpegData(compressionQuality: 1),
           let jpegImage = UIImage(data: jpegData),
           let colors = try? jpegImage.dominantColors(with: .best, algorithm: .iterative) {
            if colors.count >= minCount {
                return colors
            } else {
                resultColors = colors
            }
        }
        // Try With Original Image
        if let colors = try? dominantColors(with: .best, algorithm: .iterative) {
            if colors.count >= minCount {
                return colors
            } else {
                resultColors = colors
            }
        }
        if let colors = try? dominantColors() {
            if colors.count >= minCount {
                return colors
            } else {
                resultColors = colors
            }
        }
        return resultColors
    }
}

When the following image is added as input parameter, crash inside ColorKit happened: Снимок экрана 2024-01-16 в 16 12 20

Please find the image here

Image - IMG_6111

Could this issue be fixed? Looks like the safe check for dictionary should be added. Thanks in advance!

NatashaLavrinenko avatar Jan 16 '24 07:01 NatashaLavrinenko

I was hitting this crash for all images captured on my iOS 17 device. Patching this pull request fixed it for me: https://github.com/Boris-Em/ColorKit/pull/28/files

terribleben avatar Jul 01 '24 17:07 terribleben