调用方法
NSString *str = [self image2DataURL:[UIImage imageNamed:@"guanbi.png"]];
实现方法
- (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]];
}
网友评论