Question

I would like to know if anyone can point me in the right direction regarding what frameworks/methods to use when replacing a block of pixels in an image with another block of pixels.

For example lets say I have a simple image colored fully red and I consider my pixel block size as 5x5 pixels. Now every 3 blocks I want to replace the 3rd block with a blue colored block (5x5 pixels) so that it would result in a red image with blue blocks appearing every 3 red blocks.

I've found information regarding pixel replacement but am trying to figure out how to determine and process pixel blocks. Any advice would be appreciated.. and any code would be a wet dream.

Was it helpful?

Solution

Although it may sound like a simple question, it's not quite easy to do something like that. You need a lot of background information to get everything going. It also depends on where the image comes from, and what you want to do with it.

I will not provide you with a working example, but here's some pointers:

Reading in an image:

UIImage *img = [UIImage imageNamed:@"myimage.png"];
// make sure you added myimage.png to your project

Creating your own "graphics context" to draw on:

UIGraphicsBeginImageContext(CGSizeMake(480.0f, 320.0f)); // the size (width,height)
CGContextRef ctx = UIGraphicsGetCurrentContext();

Painting your image onto your (current) context:

[img drawAtPoint:CGPointMake(0.0f, -480.0f)]; // (draws on current context)

Doing some other painting:

CGContextBeginPath(ctx); // start a path
CGContextSetRGBStrokeColor(ctx,1,0,0,1); // red,green,blue,alpha with range 0-1
CGContextMoveToPoint(ctx,50,0); // move to beginning of path at point (50,0)
CGContextAddLineToPoint(ctx,100,100); // add a line to point (100,100)
CGContextStrokePath(ctx); // do the drawing

Transforming the bitmap context to an image again:

UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();

And then, either:

Show the image to the audience, from within a view controller:

[self.view addSubview:[[[UIImageView alloc] initWithImage:resultImage] autorelease]];

Or write the image as jpeg:

NSData *imagedata = UIImageJPEGRepresentation(img,0.8); // 0.8 = quality
[imagedata writeToFile:filename atomically:NO];

Or as PNG:

NSData *imagedata = UIImagePNGRepresentation(img);
[imagedata writeToFile:filename atomically:NO];

For those last ones you would need to have a filename, which is not so trivial either (given the phone environment you live in). That's another topic on which you'll find a lot, search for things like:

NSArray *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filename = [[path elementAtIndex:0] stringByAppendingPathComponent:@"myimage.png"];

This is the general outline, I might have made some errors but this should get you going at least.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top