Convert UIImage to NSString (and vice-versa)

梦想与她 提交于 2019-12-10 16:14:06

问题


I need a method to convert a UIImage in a NSString and then convert the NSString back to a UIImage.

Thanks.


回答1:


for >= IOS 7

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

    return [imageData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

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

    return [UIImage imageWithData:data];
}



回答2:


Convert it to a binary stream instead (NSData). This will depend on the format of your UIImage. If it's a JPEG/PNG for instance, you do:

NSData *data1 = UIImageJPEGRepresentation(image, 1.0);
NSData *data2 = UIImagePNGRepresentation(image);

UPDATE: Converting the binary data to NSString is a bad idea, that is why we have the class NSData. The OP wants to be able to send it as a data stream and then reconstruct it again; NSString will not be needed for this.




回答3:


Convert to PNG or JPEG using UIImagePNGRepresentation or UIImageJPEGRepresentation, which will return an NSData, and then convert the NSData to a string (not sure how you want to do that mapping). How about just dealing with the NSData? You can read/write that to a file.



来源:https://stackoverflow.com/questions/5849636/convert-uiimage-to-nsstring-and-vice-versa

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