Skip to content

Saving UIImage as a PNG with an Alpha Channel (with transparency) on iOS

by dkberktas on November 22nd, 2010

Say you let your user draw thing and let them go wild with their imaginations, as they probably create awesome drawings, you should probably want to save these images to somewhere.

After this short happy talk, here is the code snippet that saves your UIImage to the Documents folder with its alpha channel, if there is one. The other method is for reading that image back to an UIImage instance.

-(void)saveImageToDocs:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath2 = [NSString stringWithFormat:@"%@/%@.png", documentsDirectory, fileName];

	// If you use this method, the transparency will be lost
	//NSData* imageData = UIImageJPEGRepresentation(drawImage.image, 1.0);
	//NSData* imageData = UIImagePNGRepresentation(drawImage.image);
	//[imageData writeToFile:filePath2 atomically:NO];

	// So use this one
	[UIImagePNGRepresentation(myUIImage) writeToFile:filePath2 atomically:YES];
}

-(void)loadImageFromDocs:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath2 = [NSString stringWithFormat:@"%@/%@.png", documentsDirectory, fileName];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath2])
	{
		NSLog(@"image file exists");
		myUIImage = [UIImage imageWithContentsOfFile: filePath2];
	}
}

From → Uncategorized

2 Comments
  1. Thanks a lot mate. I have been searching for this for weeks and you gave me the solution !!

    You rule…

    Cheers from Holland.

  2. Thanks! Hope it helped.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS