encode image to base64, get a invalid base64 string (ios using base64EncodedStringWithOptions)

末鹿安然 提交于 2019-12-03 02:24:57

I think you should replace the your options parameter

Change:

NSString *imageString = [imageData base64EncodedStringWithOptions:0];

To:

NSString *imageString = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];

And just in case you'd like it:

- (NSString *)imageToNSString:(UIImage *)image
{
    NSData *data = UIImagePNGRepresentation(image);

    return [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}

- (UIImage *)stringToUIImage:(NSString *)string
{
    NSData *data = [[NSData alloc]initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];

    return [UIImage imageWithData:data];
}

Remember that this is an iOS 7 api.

replace + to %2B ios replace all + to " " space that make image invalid

also backend must handle it too

- (NSString *)base64String:(UIImage*)image {return [[UIImageJPEGRepresentation(image,1) base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed] stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];}

Yap, I find the problem is I don't encode the url.

In the post data my base64 "+" character was translate to " " character.

So I get the invalid base64 string.

Thanks Logan.

inspired from Fadi Abuzant answer here is the Swift 3 version

stringBase64 = stringBase64.replacingOccurrences(of: "+", with: "%2B")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!