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

后端 未结 4 760
误落风尘
误落风尘 2021-02-05 19:39

Here is my code.

  UIImage *img = [UIImage imageNamed:@\"white.jpeg\"];
  NSData *imageData = UIImagePNGRepresentation(img);
  NSString *imageString = [imageData         


        
相关标签:
4条回答
  • 2021-02-05 19:54

    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.

    0 讨论(0)
  • 2021-02-05 19:54

    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.

    0 讨论(0)
  • 2021-02-05 19:59

    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"];}
    
    0 讨论(0)
  • 2021-02-05 20:15

    inspired from Fadi Abuzant answer here is the Swift 3 version

    stringBase64 = stringBase64.replacingOccurrences(of: "+", with: "%2B")
    
    0 讨论(0)
提交回复
热议问题