我正在尝试保存一个UIIMage,然后检索并显示它。我已经成功地在包中保存了一个图像,从那里检索它并显示出来。我的问题来自于我试图将图像保存到磁盘(将其转换为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做些什么吗?
发布于 2011-04-19 14:59:40
试试这段代码。这对我很有效。
保存数据的。
创建保存图像的路径。
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)创建一个图像视图,并用检索到的图像加载它。
let imageView = UIImageView(image: newImage)
self.view.addSubview(imageView)发布于 2010-02-11 07:23:46
您应该能够使用UIImage的类方法
[UIImage imageWithContentsOfFile:topPathToFile]; 或
[UIImage imageWithData:data];这不管用吗?
希望这能有所帮助!
发布于 2014-02-08 09:27:00
如果这对某些人有帮助,我们可以从iOS6获得imageWithData:scale方法。要从NSData对象中获取具有正确比例的UIImage,请使用该方法,并声明用于存储原始图像的比例。例如:
CGFloat screenScale = [[UIScreen mainScreen] scale];
UIImage *image = [UIImage imageWithData:myimage scale:screenScale];在这里,myimage是存储原始图像的NSData对象。在这个例子中,我使用了屏幕的比例。如果对原始图像使用其他比例,请改用该值。
https://stackoverflow.com/questions/2240765
复制相似问题