Here is a category on UIImage I use to do just that:
- (BOOL)hasAlpha
{
CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);
return (alpha == kCGImageAlphaFirst ||
alpha == kCGImageAlphaLast ||
alpha == kCGImageAlphaPremultipliedFirst ||
alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *)dataURL
{
NSData *imageData = nil;
NSString *mimeType = nil;
if (self.hasAlpha) {
imageData = UIImagePNGRepresentation(self);
mimeType = @"image/png";
} else {
imageData = UIImageJPEGRepresentation(self, 1.0);
mimeType = @"image/jpeg";
}
return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType, [imageData base64EncodedStringWithOptions:0]];
}
This requires iOS 7 to encode the data as base64, but there are third party libraries to do the same thing.