Suppose I have a UIImage
instance that I would like to convert into a data URI and inject into a UIWebView.
I know I can convert the UIImage to PNG/JPEG NSData
using PNGRepresentation
/JPEGRepresentation
methods. But then how do I make sure that the conversion is base64? And then how do I create a string with the actual URI and headers present?
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.
Here's the Swift 5 version of @David Beck's answer in case if somebody need it:
extension UIImage {
func hasAlpha() -> Bool {
guard let cgImage = cgImage else {
return false
}
let alpha = cgImage.alphaInfo
return alpha == .first || alpha == .last || alpha == .premultipliedFirst || alpha == .premultipliedLast
}
func dataURL() -> String? {
var imageData: Data? = nil
var mimeType: String? = nil
if hasAlpha() {
imageData = self.pngData()
mimeType = "image/png"
} else {
imageData = self.jpegData(compressionQuality: 1.0)
mimeType = "image/jpeg"
}
return "data:\(mimeType ?? "");base64,\(imageData?.base64EncodedString(options: []) ?? "")"
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With