0

How do I find alpha values for the various pixels of a CGImage?

There is an array returned by the decode property of the CGImage. Would probing the values of this array be required?

Or should I look at the dataProvider property?

I want to iterate through the pixels and get the alpha value for each pixel.

Edit:

The question linked to as duplicate is an objective-c question. I only know swift.

Himanshu P
  • 9,586
  • 6
  • 37
  • 46

1 Answers1

0

You asked about CGImage, but this should be relatively straightforward to modify. I do believe probing the values of this array is required, so here is how you could go about doing that:

func imageIsEmpty(_ image: UIImage) -> Bool {
    guard let cgImage = image.cgImage,
          let dataProvider = cgImage.dataProvider else
    {
        return true
    }

    let pixelData = dataProvider.data
    let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
    let imageWidth = Int(image.size.width)
    let imageHeight = Int(image.size.height)
    for x in 0..<imageWidth {
        for y in 0..<imageHeight {
            let pixelIndex = ((imageWidth * y) + x) * 4
            let r = data[pixelIndex]
            let g = data[pixelIndex + 1]
            let b = data[pixelIndex + 2]
            let a = data[pixelIndex + 3]
            if a != 0 {
                if r != 0 || g != 0 || b != 0 {
                    return false
                }
            }
        }
    }

    return true 
 }

I found this answer by mattdedek from How to check if a uiimage is blank? (empty, transparent)

He uses this post to come up with his solution: Get Pixel Data of ImageView from coordinates of touch screen on xcode?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
ekrenzin
  • 387
  • 2
  • 12
  • The question has been updated. You should update the answer to match the new requirement. – rmaddy Oct 25 '19 at 17:02
  • There is a serious problem with this answer. It assumes the pixel data is in RGBA format taking 32-bits per pixel. That may work for some images but it's not valid for all images. – rmaddy Oct 25 '19 at 17:23
  • Thanks for adding links in the original question :) I can't comment yet, otherwise I probably would have refrained from posting an answer and simply linked to my sources... In any case, I'll think over how to improve this method for a bit. I can delete the answer as long as it's not marked as the solution, so if I don't come up with a solution to the flaw I will delete it later~ – ekrenzin Oct 25 '19 at 17:46