View Images And PDF Files In Realtime With Mac OS X Preview While Debugging iOS Apps

David Dengg recently contacted me with a unique tip that can be quite helpful if you are creating or manipulating UIImage objects and/or PDF files in your iOS app.

The basic idea is to show objects in realtime in the Preview app on your Mac development machine while your application is running in the simulator. Let me show you how this works – in the code below (from yesterday’s post on cropping an image), I create a UIImage object that is cropped from another image:

UIImage *image = [UIImage imageNamed:@"mountains.png"];
// Create rectangle from middle of current image
CGRect croprect = CGRectMake(image.size.width / 4, image.size.height / 4 ,
  (image.size.width / 2), (image.size.height / 2));
// Draw new image in current graphics context
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], croprect);
// Create new cropped UIImage
UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

Continue reading

Save UIImage Object as a PNG or JPEG File

In an earlier post on saving images from the camera to the Photo Album, a question was posed asking how to save the image to another directory other than the Photo Album. Let’s walk through one way to write a UIImage object, from the camera or otherwise, as a PNG or JPG file into the Documents directory.

Get UIImage Data as PNG or JPEG

UIKit includes two C functions, UIImageJPEGRepresentation and UIImagePNGRepresentation which will return an NSData object that represents an image in JPEG or PNG format, respectively. With this information in hand, you can then use the writeToFile method of the NSData object to write the image data to a specified path.
Continue reading

Download, Create and Display an Image from URL

This tip will show the steps to download and display an image from a remote resource. This is handy if you need to add an image as a subview, yet, the image is not part of your application bundle.

URL to Remote Image

We start by creating a URL to the remote resource:

NSURL *url = [NSURL URLWithString: 
Create UIImage from NSData

The next step is to build a UIImage using the data downloaded from the URL, which consists of an NSData object that holds the remote image contents:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]];
Putting it Together

Here’s how to wrap it all together, adding the remote image as a subview to an existing view by creating a UIImageView from the above UIImage:

NSURL *url = [NSURL URLWithString: 
UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL:url]]; 
[self.view addSubview:[[UIImageView alloc] initWithImage:image]];