iphone - NSData 到 UIImage

标签 iphone uiimage nsdata

我正在尝试保存 UIIMage,然后检索并显示它。我成功地将图像保存在 bundle 中,从那里检索它并显示。我的问题来自于当我尝试将图像保存到磁盘(将其转换为 NSData),然后检索它时。我将图像转换为 NSData 像这样......

NSData* topImageData = UIImageJPEGRepresentation(topImage, 1.0);

然后我像这样将其写入磁盘......

[topImageData writeToFile:topPathToFile atomically:NO];

然后我尝试像这样检索它......

topSubView.image = [[UIImage alloc] initWithContentsOfFile:topPathToFile];

不返回图像(大小为零)。所以我尝试了...

NSData *data = [[NSData alloc] initWithContentsOfFile:topPathToFile];
topSubView.image = [[UIImage alloc] initWithData:data];

无济于事。当我单步执行调试器时,我确实看到数据包含正确的字节数,但我对为什么没有创建我的图像感到困惑。我是不是少了一步?在转换为图像之前我需要对 NSData 执行某些操作吗?

最佳答案

试试这个代码。这对我有用。

保存数据。

创建保存图像的路径。

let libraryDirectory = NSSearchPathForDirectoriesInDomains(.libraryDirectory,
                                                               .userDomainMask,
                                                               true)[0]
let libraryURL = URL(fileURLWithPath: libraryDirectory, isDirectory: true)
let fileURL = libraryURL.appendingPathComponent("image.data")

将图像转换为数据对象并将其保存到文件中。

let data = UIImageJPEGRepresentation(myImage, 1.0)
try? data?.write(to: fileURL)

检索保存的图像

let newImage = UIImage(contentsOfFile: fileURL.relativePath)

创建一个 ImageView 并使用检索到的图像加载它。

let imageView = UIImageView(image: newImage)
self.view.addSubview(imageView)

关于iphone - NSData 到 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2240765/

相关文章:

iphone - 什么是 MKTeleportingUserLocation?

iphone - UITableViewController 控件中的多项选择

ios - SDWebImage UITableView 单元格图像不持久化

cocoa-touch - UIImage 到原始 NSData/避免压缩

ios - Obj-C 以编程方式更改 ViewController(两个 Storyboard)

iphone - 用于镜像 iphone 开发的 linux 语言

objective-c - Objective-C : How to convert CGImageRef to UIImageView?

iPhone的stretchableImageWithLeftCapWidth只产生 "D"s

ios - 检查下载的 NSData 哈希

ios - 从 BLE 获取字符串