Skip to content

Instantly share code, notes, and snippets.

@sprite2005
Created July 5, 2011 20:49
Show Gist options
  • Save sprite2005/1065886 to your computer and use it in GitHub Desktop.
Save sprite2005/1065886 to your computer and use it in GitHub Desktop.
- (BOOL) sourceImage:(UIImage*) sourceImage matchesImageNamed:(NSString*)imageName at:(CGPoint)at
{
UIImage* comparisonImage = [UIImage imageNamed:imageName];
CGImageRef comparisonImageRef = [comparisonImage CGImage];
NSUInteger comparisonImageWidth = CGImageGetWidth(comparisonImageRef);
NSUInteger comparisonImageHeight = CGImageGetHeight(comparisonImageRef);
// NSLog(@"%@ Width: %d Height: %d", imageName, comparisonImageWidth, comparisonImageHeight);
// The rectangle we want to draw
CGRect sourceRect = CGRectMake(at.x, at.y, comparisonImageWidth, comparisonImageHeight);
CGRect comparisonRect = CGRectMake(0, 0, comparisonImageWidth, comparisonImageHeight);
// Create the data for the source pixels
unsigned int *sourceImagePixels = (unsigned int*)malloc(comparisonImageHeight * comparisonImageWidth * 4);
memset(sourceImagePixels, 0, comparisonImageHeight * comparisonImageWidth * 4);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef sourceImageRef = CGImageCreateWithImageInRect([sourceImage CGImage], sourceRect);
CGContextRef sourceImageContext = CGBitmapContextCreate(sourceImagePixels, comparisonImageWidth, comparisonImageHeight, 8, comparisonImageWidth * 4, colorSpace, kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(sourceImageContext, comparisonRect, sourceImageRef);
// Create the data for the comparison image
unsigned int* comparisonImagePixels = (unsigned int*)malloc(comparisonImageWidth * comparisonImageWidth * 4);
memset(comparisonImagePixels, 0, comparisonImageHeight * comparisonImageWidth * 4);
CGContextRef comparisonImageContext = CGBitmapContextCreate(comparisonImagePixels, comparisonImageWidth, comparisonImageHeight, 8, comparisonImageWidth * 4, colorSpace, kCGBitmapByteOrder32Big | kCGImageAlphaNoneSkipLast);
CGContextDrawImage(comparisonImageContext, comparisonRect, comparisonImageRef);
// Compare the two images
BOOL match = NO;
if (!memcmp(sourceImagePixels, comparisonImagePixels, comparisonImageHeight * comparisonImageWidth * 4)) {
match = YES;
}
// Clean up memory
free(comparisonImagePixels);
free(sourceImagePixels);
CGColorSpaceRelease(colorSpace);
CGContextRelease(sourceImageContext);
CGContextRelease(comparisonImageContext);
CGImageRelease(sourceImageRef);
return match;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment