使用高度信息迭代UIImage的各个像素 [英] Iterate over individual pixels of a UIImage with height information

查看:92
本文介绍了使用高度信息迭代UIImage的各个像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自动裁剪在其上方和下方具有无关白色的图像。我试图迭代图像的像素,找到第一个非白色像素,将其设置为从顶部裁剪的适当高度,然后使用最后一个非白色像素作为从中裁剪的适当高度底部。

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.

我尝试使用 CGBitmapContextGetData 生成单个像素,但据我所知,这只保留了图像的RGB颜色使像素高度的信息丢失。

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.

有没有人知道在能够访问这些图片的高度信息的同时迭代UIImage的各个像素的方法?谢谢。

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.

推荐答案

您可以从UIImage的cgImage表示中获取像素。宽度和高度可在UIImage的大小字段中找到。对于每个像素,请检查该像素的RGBA值。如果它们不是全部255,那么它是非白色像素。

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
    }

这篇关于使用高度信息迭代UIImage的各个像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆