开发者

Convert UIImage to NSString (and vice-versa)

开发者 https://www.devze.com 2023-03-02 16:15 出处:网络
I need a method to convert a开发者_StackOverflow UIImage in a NSString and then convert the NSString back to a UIImage.

I need a method to convert a开发者_StackOverflow UIImage in a NSString and then convert the NSString back to a UIImage.

Thanks.


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];
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消