orange_juice orange_juice - 1 month ago 5
iOS Question

Iterate over individual pixels of a UIImage with height information

I'm trying to automatically crop an image that has extraneous white color above and below it. I'm trying to iterate over the pixels of the image to find the first non-white pixel to set that as the appropriate height to crop from the top, and then using the last non-white pixel as the appropriate height to crop from the bottom.

I've attempted using

CGBitmapContextGetData
to generate the individual pixels but as far as I can tell this only preserves the RGB color of the pictures so the information of the pixel height's is lost.

Does anyone know any ways of iterating over individual pixels of a UIImage while being able to access the height information of those pictures? Thank you.

Answer

You can grab the pixels from the cgImage representation of the UIImage. The width and height are found on the size field of the UIImage. For each pixel, check the RGBA values for that pixel. If they aren't all 255 then its a non white pixel.

    func firstNonWhitePixel(image: UIImage) -> CGPoint? {
        let width = Int(image.size.width)
        let height = Int(image.size.height)
        if let cfData = image.cgImage?.dataProvider?.data, let pointer = CFDataGetBytePtr(cfData) {
            for x in 0..<width {
                for y in 0..<height {
                    let pixelAddress = x * 4 + y * width * 4
                    if pointer.advanced(by: pixelAddress).pointee != UInt8.max ||     //Red
                       pointer.advanced(by: pixelAddress + 1).pointee != UInt8.max || //Green
                       pointer.advanced(by: pixelAddress + 2).pointee != UInt8.max || //Blue
                       pointer.advanced(by: pixelAddress + 3).pointee != UInt8.max  {  //Alpha
                        return CGPoint(x: x, y: y)
                    }
                }
            }
        }
        return nil
    }