Domanda

I want to get the pixels of an image in ios.

I know how to do it in android, I am looking for the equivalent method for ios.

http://developer.android.com/reference/android/graphics/Bitmap.html#getPixels(int[], int, int, int, int, int, int)

I found a bunch of examples code for ios, but none were as clean as in the android framework. So I am guessing that there is a better, simpler way which is handled mostly by the framework.

È stato utile?

Soluzione

I used this way

- (void) imagePixel:(UIImage *)image
{

    struct pixel {
        unsigned char r, g, b, a;
    };


    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    CGImageRef imageRef = image.CGImage;

    size_t width = CGImageGetWidth(imageRef);
    size_t height = CGImageGetHeight(imageRef);

    struct pixel *pixels = (struct pixel *) calloc(1, sizeof(struct pixel) * width * height);


    size_t bytesPerComponent = 8;
    size_t bytesPerRow = width * sizeof(struct pixel);

    CGContextRef context = CGBitmapContextCreate(pixels, width, height, bytesPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    unsigned long numberOfPixels = width * height;

    if (context != NULL) {
        for (unsigned i = 0; i < numberOfPixels; i++) {
            //you can add code here
            pixels[i].r;
            pixels[i].g;
            pixels[i].b;
        }


        free(pixels);
        CGContextRelease(context);
    }

    CGColorSpaceRelease(colorSpace);

}

Update:

Yes, you can recreating image before release context and free pixel by

CGImageRef imageR = CGBitmapContextCreateImage(context);
UIImage *outputImage = [UIImage imageWithCGImage:imageR];

at the end you should release imageR with

CGImageRelease(imageR)

Altri suggerimenti

-(NSArray*)getPixelsFromImage:(UIImage*)image
{
NSMutableArray *pixelData=[NSMutableArray new];
for (int y = 0; y<image.size.height; y+=1) {
   for (int x = 0; x<image.size.width; x+=1) {
           CGImageRef tmp = CGImageCreateWithImageInRect(image.CGImage, CGRectMake(x, y, 1, 1));
           UIImage *part=[UIImage imageWithCGImage:tmp];
           [pixelData addObject:part];
       }

   }
return [pixelData copy];
}

This is returning an array of 1x1 UIImages. Maybe it will suit you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top