2015-11-20 16 views

回答

1
/** 
* Structure to keep one pixel in RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA format 
*/ 

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

/** 
* Process the image and return the number of pixels in it. 
*/ 

- (NSUInteger) processImage: (UIImage*) image withRed:(NSUInteger)r green:(NSUInteger)g blue:(NSUInteger)b 
{ 
    NSUInteger numberOfPixels = 0; 

    // Allocate a buffer big enough to hold all the pixels 

    struct pixel* pixels = (struct pixel*) calloc(1, image.size.width * image.size.height * sizeof(struct pixel)); 
    if (pixels != nil) 
    { 
     // Create a new bitmap 

     CGContextRef context = CGBitmapContextCreate(
      (void*) pixels, 
      image.size.width, 
      image.size.height, 
      8, 
      image.size.width * 4, 
      CGImageGetColorSpace(image.CGImage), 
      kCGImageAlphaPremultipliedLast 
     ); 

     if (context != NULL) 
     { 
      // Draw the image in the bitmap 

      CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, image.size.width, image.size.height), image.CGImage); 

      // Now that we have the image drawn in our own buffer, we can loop over the pixels to 
      // process it. This simple case simply counts all pixels that have a pure red component. 

      // There are probably more efficient and interesting ways to do this. But the important 
      // part is that the pixels buffer can be read directly. 

      NSUInteger p = image.size.width * image.size.height; 

      while (p > 0) { 
       if (pixels->r == r && pixels->g == g && pixels->b == b) { 
        numberOfPixels++; 
       } 
       pixels++; 
       p--; 
      } 

      CGContextRelease(context); 
     } 

     free(pixels); 
    } 

    return numberOfPixels; 
} 

用途:

NSUInteger numberOfSpecificColorPixels = [self processImage: [UIImage imageNamed: @"testImage.png" withRed:232 green:212 blue:192]]; 

这会给你的特定颜色的像素,然后你就可以按照您的要求

+0

你是男人使用的号码,我欠你一个啤酒。 – Dalton

+0

感谢高兴它帮助:) – Usama

相关问题