4

I know similar question have been asked before.

What I want is to get the RGB pixel value of the Image Inside the Imageview, so it can be any image that pixel values we want to get.

This is what I have used to get the point where the image is clicked.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [touches anyObject];

    if ([touch tapCount] == 2) {
        //self.imageView.image = nil;
        return;
    }

    CGPoint lastPoint = [touch locationInView:self.imageViewGallery];
    NSLog(@"%f",lastPoint.x);
    NSLog(@"%f",lastPoint.y);

} 

And To get the Image I have Pasted this code.

+ (NSArray*)getRGBAsFromImage:(UIImage *)image atX:(int)xx andY:(int)yy count:(int)count
{

 NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

      /** It requires to get the image into your data buffer, so how can we get the `ImageViewImage` **/

CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
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), imageRef);
CGContextRelease(context);

// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
for (int ii = 0 ; ii < count ; ++ii)
{
    CGFloat red   = (rawData[byteIndex]     * 1.0) / 255.0;
    CGFloat green = (rawData[byteIndex + 1] * 1.0) / 255.0;
    CGFloat blue  = (rawData[byteIndex + 2] * 1.0) / 255.0;
    CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
    byteIndex += 4;

    UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
    [result addObject:acolor];
}

free(rawData);

return result;
}

I am new to ios so please explain and It and suggesting some tutorial will be great.

byJeevan
  • 3,728
  • 3
  • 37
  • 60
Exception
  • 249
  • 1
  • 4
  • 17

4 Answers4

5

Use this example article. It is talking about a color picker using images. You can understand required info very easily from it. Helped me in my app. Let me know if any help/suggestion needed ..:)

EDIT:

update your getPixelColorAtLocation: like this. It will give you correct color then.

- (UIColor*) getPixelColorAtLocation:(CGPoint)point {
    UIColor* color = nil;
    CGImageRef inImage = self.image.CGImage;
    // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    if (cgctx == NULL) { return nil; /* error */ }

    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}};
/** Extra Added code for Resized Images ****/
    float xscale = w / self.frame.size.width;
    float yscale = h / self.frame.size.height;
    point.x = point.x * xscale;
    point.y = point.y * yscale;
 /** ****************************************/

/** Extra Code Added for Resolution ***********/
    CGFloat x = 1.0;
    if ([self.image respondsToSelector:@selector(scale)]) x = self.image.scale;
/*********************************************/
    // Draw the image to the bitmap context. Once we draw, the memory 
    // allocated for the context for rendering will then contain the 
    // raw image data in the specified color space.
    CGContextDrawImage(cgctx, rect, inImage); 

    // Now we can get a pointer to the image data associated with the bitmap
    // context.
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        //offset locates the pixel in the data from x,y. 
        //4 for 4 bytes of data per pixel, w is width of one row of data.
//      int offset = 4*((w*round(point.y))+round(point.x));


        int offset = 4*((w*round(point.y))+round(point.x))*x; //Replacement for Resolution
        int alpha =  data[offset];
        int red = data[offset+1]; 
        int green = data[offset+2]; 
        int blue = data[offset+3]; 
        NSLog(@"offset: %i colors: RGB A %i %i %i  %i",offset,red,green,blue,alpha);
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
    }

    // When finished, release the context
    CGContextRelease(cgctx); 
    // Free image data memory for the context
    if (data) { free(data); }

    return color;
}

Let me know this fix does not work .. :)

Here is the GitHub for my code. Use it to implement picker image. Let me know if more info needed

Prince Agrawal
  • 3,619
  • 3
  • 26
  • 41
  • I have followed the link But I am getting the wrong pixel Values. – Exception Jan 10 '14 at 11:49
  • ya.. there is a small edit needed in the code. the edit needed is mentioned in the comments of the article. However I'll copy the edit in my answer too. Check it in 5 mins. :) – Prince Agrawal Jan 10 '14 at 12:24
  • 1
    like I have added `CGRect frame = self.imageViewGallery.frame;` before editing – Exception Jan 10 '14 at 13:31
  • can we add more functionality with it like a circle pointer that move upon the Image and a container that fills the selected color. – Exception Jan 10 '14 at 15:01
  • Ya sure.. I've implemented exactly like what you want to implement. But I'd be able to share code with you after 12 Hours only. It's in my office. If possible, remind me by leaving a comment here after 12 hours ..:) – Prince Agrawal Jan 10 '14 at 15:08
2

Just use this method, it works for me:

- (UIColor*) getPixelColorAtLocation:(CGPoint)point 
{

    UIColor* color = nil;

    CGImageRef inImage;

    inImage = imgZoneWheel.image.CGImage;


    // Create off screen bitmap context to draw the image into. Format ARGB is 4 bytes for each pixel: Alpa, Red, Green, Blue
    CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];
    if (cgctx == NULL) { return nil; /* error */ }

    size_t w = CGImageGetWidth(inImage);
    size_t h = CGImageGetHeight(inImage);
    CGRect rect = {{0,0},{w,h}};


    // Draw the image to the bitmap context. Once we draw, the memory 
    // allocated for the context for rendering will then contain the 
    // raw image data in the specified color space.
    CGContextDrawImage(cgctx, rect, inImage); 

    // Now we can get a pointer to the image data associated with the bitmap
    // context.
    unsigned char* data = CGBitmapContextGetData (cgctx);
    if (data != NULL) {
        //offset locates the pixel in the data from x,y. 
        //4 for 4 bytes of data per pixel, w is width of one row of data.
        int offset = 4*((w*round(point.y))+round(point.x));
        alpha =  data[offset]; 
        int red = data[offset+1]; 
        int green = data[offset+2]; 
        int blue = data[offset+3]; 
        color = [UIColor colorWithRed:(red/255.0f) green:(green/255.0f) blue:(blue/255.0f) alpha:(alpha/255.0f)];
    }

    // When finished, release the context
    //CGContextRelease(cgctx); 
    // Free image data memory for the context
    if (data) { free(data); }

    return color;
}

Just use like this:

UIColor *color = [self getPixelColorAtLocation:lastPoint];
Lapinou
  • 1,467
  • 2
  • 20
  • 39
  • Getting 2 Warnings and where the app is crashed 1- Instance method '-createARGBBitmapContextFromImage:' not found (return type defaults to 'id'). 2- Incompatible pointer types initializing 'CGContextRef' (aka 'struct CGContext *') with an expression of type 'id'. on this line ` CGContextRef cgctx = [self createARGBBitmapContextFromImage:inImage];` Can you tell me what essential methods are required. – Exception Jan 09 '14 at 20:47
  • 1
    Sure, just follow the link of @achievelimitless: http://www.markj.net/iphone-uiimage-pixel-color/, it's the tutorial with full code you need ;) – Lapinou Jan 10 '14 at 09:31
  • 1
    @quickApp Don't worry.. I voted up for Lapinou. Thanx for your nice gesture ..:) – Prince Agrawal Jan 10 '14 at 14:50
0

If you try to get color from image through CGBitmapContextGetData and set, for example, in background of view, this will be different colors in iPhone 6 and later. In iPhone 5 everything will be ok) More information about this Getting the right colors in your iOS app

This solution through UIImage give you right color:

- (UIColor *)getColorFromImage:(UIImage *)image pixelPoint:(CGPoint)pixelPoint {

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(pixelPoint.x, pixelPoint.y, 1.f, 1.f));
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);

    return [UIColor colorWithPatternImage:croppedImage];

}
-2

You want to know how to get the image from an image view?

UIImageView has a property, image. Simply use that property.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • no my dear look e.g there is an imageView.image contains any Image lets say your current stack profile picture,If we pass it to imageview then we should have some pointer over it which when click on eye dot return the rgb pixel value of that whatever it is brown,blue eye color. – Exception Jan 09 '14 at 20:21