Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a UIImage into a data URI

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?

like image 550
Andrew Lauer Barinov Avatar asked Jun 19 '13 03:06

Andrew Lauer Barinov


2 Answers

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.

like image 123
David Beck Avatar answered Nov 03 '22 12:11

David Beck


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: []) ?? "")"
}

}

like image 2
Sash Avatar answered Nov 03 '22 12:11

Sash