这是我的代码。
UIImage *img = [UIImage imageNamed:@"white.jpeg"];
NSData *imageData = UIImagePNGRepresentation(img);
NSString *imageString = [imageData base64EncodedStringWithOptions:0];
NSLog(@"%@", imageString);
而且我总是得到无效的base64字符串,其中包含空格。
iVBORw0KGgoAAAANSUhEUgAAARMAAAC3CAIAAAC MS2jAAAAHGlET1QAAAACAAAAAAAAAFwAAAAoAAAAXAAAAFsAAAMC oRdmgAAAs5JREFUeAHs1tFKI1EABFH//5NNVh02uA LQhwoCZ0zj5LbTlffInl58yCAwM8JvPz8iBMIIPDGHJcAgTMEmHOGmjMIMMcdQOAMAeacoeYMAsxxBxA4Q4A5Z6g5gwBz3IGHIPD zfMQL/fVSzDnKyr 9usEvhHn/ddf5N5/yJx7SflcSoA5KV7hz0Lgn0gPW9h3zsNO81wvdr1e/3w R3PmPNf82p4mcLlcDnlu/txCbvKcDqwP s6pCcu/i8Bhzn/yMOcucD705ARe/z43eY5fbQcN5jz5lVB/k4Bfa5u7alUTYE5NWP4mAeZs7qpVTYA5NWH5mwSYs7mrVjUB5tSE5W8SYM7mrlrVBJhTE5a/SYA5m7tqVRNgTk1Y/iYB5mzuqlVNgDk1YfmbBJizuatWNQHm1ITlbxJgzuauWtUEmFMTlr9JgDmbu2pVE2BOTVj JgHmbO6qVU2AOTVh ZsEmLO5q1Y1AebUhOVvEmDO5q5a1QSYUxOWv0mAOZu7alUTYE5NWP4mAeZs7qpVTYA5NWH5mwSYs7mrVjUB5tSE5W8SYM7mrlrVBJhTE5a/SYA5m7tqVRNgTk1Y/iYB5mzuqlVNgDk1YfmbBJizuatWNQHm1ITlbxJgzuauWtUEmFMTlr9JgDmbu2pVE2BOTVj JgHmbO6qVU2AOTVh ZsEmLO5q1Y1AebUhOVvEmDO5q5a1QSYUxOWv0mAOZu7alUTYE5NWP4mAeZs7qpVTYA5NWH5mwSYs7mrVjUB5tSE5W8SYM7mrlrVBJhTE5a/SYA5m7tqVRNgTk1Y/iYB5mzuqlVNgDk1YfmbBJizuatWNQHm1ITlbxJgzuauWtUEmFMTlr9JgDmbu2pVE2BOTVj JgHmbO6qVU2AOTVh ZsEmLO5q1Y1AebUhOVvEmDO5q5a1QSYUxOWv0mAOZu7alUTYE5NWP4mAeZs7qpVTeADAAD//66TqMcAAAIISURBVO3TsQ0AAAjDMP4/GnEDmc3exSKzjgCBv8D8JxYECKxyPAGBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCyilqNgSU4wcIFAHlFDUbAsrxAwSKgHKKmg0B5fgBAkVAOUXNhoBy/ACBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCyilqNgSU4wcIFAHlFDUbAsrxAwSKgHKKmg0B5fgBAkVAOUXNhoBy/ACBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCyilqNgSU4wcIFAHlFDUbAsrxAwSKgHKKmg0B5fgBAkVAOUXNhoBy/ACBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCyilqNgSU4wcIFAHlFDUbAsrxAwSKgHKKmg0B5fgBAkVAOUXNhoBy/ACBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCyilqNgSU4wcIFAHlFDUbAsrxAwSKgHKKmg0B5fgBAkVAOUXNhoBy/ACBIqCcomZDQDl gEARUE5RsyGgHD9AoAgop6jZEFCOHyBQBJRT1GwIKMcPECgCB/GnRcSfso/fAAAAAElFTkSuQmCC
如此迷茫。
当我尝试删除base64字符串中的空格并对其进行解码时。
我无法获得原始图片。
最佳答案
我认为您应该替换您的options参数
更改:
NSString *imageString = [imageData base64EncodedStringWithOptions:0];
至:
NSString *imageString = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
以防万一您想要它:
- (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];
}
请记住,这是一个iOS 7 API。