画像base 64符号化iOS
/**
*
*
* @param image
* @param size ( )
*
* @return
*/
- (NSData *)zh_compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size
{
NSData *data = UIImageJPEGRepresentation(image, 1.f);
CGFloat dataKBytes = data.length / 1000.f;
CGFloat maxQuality = .9f;
CGFloat lastData = dataKBytes;
while (dataKBytes > size && maxQuality > .01f)
{
maxQuality -= .01f;
data = UIImageJPEGRepresentation(image, maxQuality);
dataKBytes = data.length / 1000.f;
NSLog(@" :%fKB", dataKBytes);
if (lastData == dataKBytes)
{
break;
}
else
{
lastData = dataKBytes;
}
}
return data;
}
// base64 ,// “+”,“+” ,
- (NSString *)encode:(NSString *)str
{
return (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)str, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
}
メソッドを呼び出しbase 64符号化
NSData *imageData = [self zh_compressOriginalImage:image toMaxDataSizeKBytes:80.f];
CGFloat len = [imageData length] / 1000.f;
if (len > 100.f){
[ShowTool showHud:@" " view:self.view];
return;
}
// base64
NSString *imageBase64Str = [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
imageBase64Str = [self encode:imageBase64Str];