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

后端 未结 4 745
误落风尘
误落风尘 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.

提交回复
热议问题