import UIKit

public extension UIImage {
    func squared() -> UIImage? {
        guard size.width != size.height else { return self }
        guard let cgImage = cgImage else { return nil }

        let length = min(cgImage.width, cgImage.height)
        let x = cgImage.width / 2 - length / 2
        let y = cgImage.height / 2 - length / 2
        let rect = CGRect(x: x, y: y, width: length, height: length)

        guard let cropped = cgImage.cropping(to: rect) else { return nil }

        return UIImage(cgImage: cropped, scale: scale, orientation: imageOrientation)
    }
}
