Base64图片与UIImage的相互转化


Base64图片 -> UIImage

- (UIImage *) dataURL2Image: (NSString *) imgSrc
{
    NSURL *url = [NSURL URLWithString: imgSrc];
    NSData *data = [NSData dataWithContentsOfURL: url];
    UIImage *image = [UIImage imageWithData: data];

    return image;
}


 
  

UIImage -> Base64图片

 
  
- (BOOL) imageHasAlpha: (UIImage *) image
{
    CGImageAlphaInfo alpha = CGImageGetAlphaInfo(image.CGImage);
    return (alpha == kCGImageAlphaFirst ||
            alpha == kCGImageAlphaLast ||
            alpha == kCGImageAlphaPremultipliedFirst ||
            alpha == kCGImageAlphaPremultipliedLast);
}
- (NSString *) image2DataURL: (UIImage *) image
{
    NSData *imageData = nil;
    NSString *mimeType = nil;

    if ([self imageHasAlpha: image]) {
        imageData = UIImagePNGRepresentation(image);
        mimeType = @"image/png";
    } else {
        imageData = UIImageJPEGRepresentation(image, 1.0f);
        mimeType = @"image/jpeg";
    }

    return [NSString stringWithFormat:@"data:%@;base64,%@", mimeType,
           [imageData base64EncodedStringWithOptions: 0]];

}


 
  

参考资料

  • http://stackoverflow.com/questions/11251340/convert-image-to-base64-string-in-ios
  • http://stackoverflow.com/questions/17182290/converting-a-uiimage-into-a-data-uri

你可能感兴趣的:(obj-c)