Home > Blockchain >  Image get pixel RGBA
Image get pixel RGBA

Time:02-23

I have Swift code that shows the first pixel from RGBA of UIImage:

let cgImage = image.cgImage
let data = cgImage.dataProvider?.data
let dataPtr = CFDataGetBytePtr(data)

let components = (
    dataPtr[0],
    dataPtr[1],
    dataPtr[p2],
    dataPtr[3]
)

when I print the value of components I get:

  - .0 : 220
  - .1 : 188
  - .2 : 129
  - .3 : 255

I want to convert this code and use it on Objective-C project, so I run this code on the same image:

CGImageRef cgImage = image.CGImage;
CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
UInt8 * dataPtr = (UInt8 *) CFDataGetBytePtr(data);

UInt8 components[4] = {
    dataPtr[0],
    dataPtr[1],
    dataPtr[2],
    dataPtr[3]
};

And when I print it I get:

ܼ\x81\xff\U00000004

Any idea how I can get the value I get in the swift value?

CodePudding user response:

If you're printing it through NSLog, you can specify the format as such:

    UIImage *image = [UIImage imageNamed:@"Aurora"];
    CGImageRef cgImage = image.CGImage;
    CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(cgImage));
    uint8_t *dataPtr = (uint8_t *) CFDataGetBytePtr(data);

    uint8_t components[4] = {
        dataPtr[0],
        dataPtr[1],
        dataPtr[2],
        dataPtr[3]
    };
    for (int i = 0; i < 4; i  ) {
        NSLog(@"index %i val %hhu", i, components[i]);
    }

Which gives this output for me (for my example image):

index 0 val 20
index 1 val 39
index 2 val 55
index 3 val 255

If you're print it out on the lldb (using p/po/frame variable) there are certain default type formatters applied. You can see them using this command: type summary list

You can add your own custom summary using this command: type summary add

https://lldb.llvm.org/use/variable.html#type-summary

In this instance, you should be able to do something like this:

type summary add --summary-string "0=${var[0]%u}, 1=${var[1]%u}, 2=${var[2]%u}, 3=${var[3]%u}" 'uint8_t [4]'

Your defined type summary will be listed under the "default" category of type summary list.

Category: default
-----------------------
uint8_t [4]: `0=${var[0]%u}, 1=${var[1]%u}, 2=${var[2]%u}, 3=${var[3]%u}`

Then when you breakpoint and po components it will print out using the custom type summary defined:

(lldb) po components
0=20, 1=39, 2=55, 3=255

You can delete the type summary using the type summary delete <summary name> (i.e type summary delete "uint8_t [4]") or delete all custom type summaries using type summary clear.

There is most likely an easier way to do what you're trying to in the rest of the documentation from the link above, but using some of the custom format stuff in the document wasn't working right away for me.

  • Related