Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C traverse pixels in an image vertically

I'm a little confused at the moment, first time poster here on stack overflow. I'm brand new to objective C but have learned a lot from my coworkers. What I'm trying to do is traverse a bmContext vertically shifting horizontally by 1 pixel after every vertical loop. Heres some code:

NSUInteger width = image.size.width;
NSUInteger height = image.size.height;
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = width * bytesPerPixel;
NSUInteger bytesPerColumn = height * bytesPerPixel;

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef bmContext = CGBitmapContextCreate(NULL, width, height, 8, bytesPerRow,     colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = width, .size.height = height}, image.CGImage);

UInt8* data = (UInt8*)CGBitmapContextGetData(bmContext);

const size_t bitmapByteCount = bytesPerRow * height;

struct Color {
    UInt8 r;
    UInt8 g;
    UInt8 b;
};

for (size_t i = 0; i < bytesPerRow; i += 4) //shift 1 pixel
{
    for (size_t j = 0; j < bitmapByteCount; j += bytesPerRow) //check every pixel in column
    {
        struct Color thisColor = {data[j + i + 1], data[j + i + 2], data[j + i + 3]};
    }
}

in java it looks something like this, but I have no interest in the java version it's just to emphasis my true question. I only care about the objective c code.

for (int x = 0; x = image.getWidth(); x++)
{
    for (int y = 0; y = image.getHeight(); y++)
    {
        int rgb = image.getRGB(x, y);
        //do something with pixel
    }
}

Am I really shifting one unit horizontally and then checking all vertical pixels and then shifting again horizontally? I thought I was but my results seem to be a little off. In java and c# achieving a task was rather simple, if anyone knows a simpler way to do this in Objective C please let me know. Thanks in advance!

like image 437
Xav Avatar asked Dec 01 '25 02:12

Xav


1 Answers

The way you are getting at the pixels seems to be off.

If I'm understanding correctly, you just want to iterate through every pixel in the image, column by column. Right? This should work:

for (size_t i = 0; i < CGBitmapContextGetWidth(bmContext); i++)
{
    for (size_t j = 0; j < CGBitmapContextGetHeight(bmContext); j++)
    {
        int pixel = j * CGBitmapContextGetWidth(bmContext) + i;
        struct Color thisColor = {data[pixel + 1], data[pixel + 2], data[pixel + 3]};
    }
}
like image 113
Dima Avatar answered Dec 03 '25 20:12

Dima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!