将 UIImage 转换为 NSString(反之亦然)

发布于 11-04 13:34 字数 75 浏览 4 评论 0原文

我需要一种方法来转换 NSString 中的 UIImage,然后将 NSString 转换回 UIImage。

谢谢。

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

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

送君千里2024-11-11 13:34:28

对于 >= 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];
}

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];
}
朕就是辣么酷2024-11-11 13:34:28

将其转换为二进制流 (NSData)。这将取决于您的 UIImage 的格式。例如,如果它是 JPEG/PNG,您可以执行以下操作:

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

更新:将二进制数据转换为 NSString 是一个坏主意,这就是我们拥有类 NSData 的原因。 OP希望能够将其作为数据流发送,然后再次重建;为此不需要 NSString

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.

嗫嚅2024-11-11 13:34:28

使用 UIImagePNGRepresentation 或 UIImageJPEGRepresentation 转换为 PNG 或 JPEG,这将返回 NSData,然后将 NSData 转换为字符串(不确定您想要如何进行映射)。只处理 NSData 怎么样?您可以将其读/写到文件中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文