图片base64 编码 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 );
}

调用方法并进行base64编码

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]; 

你可能感兴趣的:(总结,项目)