Iterate over individual pixels of a UIImage with height information

守給你的承諾、 提交于 2019-12-25 16:44:10

问题


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.


回答1:


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
    }


来源:https://stackoverflow.com/questions/40160298/iterate-over-individual-pixels-of-a-uiimage-with-height-information

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!