Reading and editing pixels of image on iPhone

╄→尐↘猪︶ㄣ 提交于 2019-12-11 16:31:08

问题


Curious about how to read and edit a picture's pixels on the iPhone. Am I better of using an array of points with colours?

I want to do things like.. if a CGPoint intersects with a "brown" spot on the picture, set the colour of all brown pixels in a radius to white. More questions to come, but this is a start.

Cheers


回答1:


The picture data is available to you as precisely that -- a two-dimensional array of pixels, each pixel being represented by a 32 bit integer. For each of the color components (red, green, blue, and alpga) there is an 8 bit value. The ordering of these 8-bit-wide values within the 32 bit integer varies with the format of the picture data. The apple doc about all this is really good. While there is some attractive Apple stuff using CGDataProviderCopyData to give you a pointer into the actual data storage of a UIImage, in practice this can be a headache, because the format of that internal storage can vary widely from one image to the next. In practice, most people doing image processing seem to use this approach:

    CGImageRef image = [UIImage CGImage];
    NSUInteger width = CGImageGetWidth(image);
    NSUInteger height = CGImageGetHeight(image);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData_ = malloc(height * width * 4);
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel_ * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height));
    CGContextRelease(context);

    //  rawData contains image data in the RGBA8888 format.

    // for any pixel at coordinate x,y -- the value is
    // 

    int pixelIndex = (bytesPerRow * y) + x * bytesPerPixel;
    unsigned char red = rawData[pixelIndex];
    green = rawData[pixelIndex + 1];
    blue = rawData[pixelIndex + 2];
    alpha = rawData[pixelIndex + 3];


来源:https://stackoverflow.com/questions/4357902/reading-and-editing-pixels-of-image-on-iphone

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