3

I want to get the locations of the pixels in a UIImage whose color matches a specified color.

For example, I want to find the position(x, y) of the pixels of this color: [UIColor colorWithRed:255 green:0 blue:0 alpha:1].

CGPoint point = getFirstPixelOfColor([UIColor colorWithRed:255 green:0 blue:0 alpha:1].CGColor);
Bo A
  • 3,144
  • 2
  • 33
  • 49
Suge
  • 2,808
  • 3
  • 48
  • 79

1 Answers1

2

Add UIImage-Utils to your project. Then get the color of x,y like this:

CGFloat imageWidth = image.size.width;
NSData *imageData = [UIImage bytesFromImage:image]
Byte *bytes = (Byte *)imageData.bytes;
CGFloat red    = bytes[redOffset   (x, y, imageWidth)] / 255.0f;
CGFloat green  = bytes[greenOffset (x, y, imageWidth)] / 255.0f;
CGFloat blue   = bytes[blueOffset  (x, y, imageWidth)] / 255.0f;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];

Store the x,y of the colors matching the color you are looking for. Repeat for every x,y in the image.

Jano
  • 62,815
  • 21
  • 164
  • 192
  • I want to find the point which matches the color I'm looking for, but not to find color of the specified point. – Suge Aug 11 '13 at 13:57
  • If you think about it, to find where one given color is, you have to iterate all the positions, extract the color of each position, and see if it matches the color you are looking for. There is no API that is going to do that work for you. – Jano Aug 11 '13 at 14:41
  • Your answer was very helpful to me. Thanks a ton! – Sergey Mell Oct 23 '20 at 21:48