Monday, January 26, 2009

Objective-C versus C#, part 2: Loading, rotating, and saving an image

 

In this example, I’ll compare Objective-C/Cocoa Touch to C#/.NET in their ability to load an image from a file, rotate it 90 degrees, and then save the modified image.  Both platforms are perfectly capable of performing this task.  One of them, however, sucks orders of magnitude less.  I’ll leave it as an exercise to the reader to decide to which I’m referring.  I’ll list the C# example first this time, since I wouldn’t want to be accused of favoritism.  In fairness, I should point out that for the Objective-C version, I cut some corners.  By using a UIImageView to house the image, I saved many lines of code that would result from applying transforms to the graphics context directly.

C#/.NET

Image myImage = Image.FromFile(@"c:\myImage.png");
myImage.RotateFlip(RotateFlipType.Rotate90FlipNone);
myImage.Save(@"c:\newImage.png");

Objective-C/Cocoa Touch

UIImage* myImage = [UIImage imageNamed:@"myImage.png"];
UIImageView* imageView = [[UIImageView alloc] initWithImage:myImage];
[imageView setTransform:CGAffineTransformMakeRotation(M_PI / 2.0)];

CGSize newImageSize = CGSizeMake(myImage.size.y, myImage.size.x);
UIGraphicsBeginImageContext(newImageSize);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage* newImage = [UIGraphicsGetImageFromCurrentImageContext() retain];
UIGraphicsEndImageContext();

[UIImagePNGRepresentation(newImage) writeToFile:@"myNewImage.png" atomically:YES];

[imageView release];
[newImage release];

2 comments:

Florent Pillet said...

Your example is correct, but hides the fact that the price paid here is for an API (CoreGraphics) orders of magnitude more powerful than what you can't even dream of doing with .NETCF.

Try imaging bezier paths with rounded caps in .NETCF for example. Good luck. Because yes, what we're really comparing here is frameworks for mobile development.

Vargo said...

I actually don't have much experience with .NETCF, but I do loathe the Windows Mobile platform. It's a bit unfair of me to compare a mobile framework with a desktop framework, but is there a better option for Mac desktop development? If so, I can eat my words.