保存图像在NSUserDefaults?

是否有可能将图像保存为NSUserDefaults作为一个对象,然后检索进一步使用?

注意! 如果您正在iOS8 / XCODE6下工作,请参阅下面的更新

对于那些仍然在寻找答案的人是在NSUserDefaults中保存图像的“明智”的代码。 你不应该直接将图像数据保存到NSUserDefaults!

写数据:

 // Get image data. Here you can use UIImagePNGRepresentation if you need transparency NSData *imageData = UIImageJPEGRepresentation(image, 1); // Get image path in user's folder and store file with name image_CurrentTimestamp.jpg (see documentsPathForFileName below) NSString *imagePath = [self documentsPathForFileName:[NSString stringWithFormat:@"image_%f.jpg", [NSDate timeIntervalSinceReferenceDate]]]; // Write image data to user's folder [imageData writeToFile:imagePath atomically:YES]; // Store path in NSUserDefaults [[NSUserDefaults standardUserDefaults] setObject:imagePath forKey:kPLDefaultsAvatarUrl]; // Sync user defaults [[NSUserDefaults standardUserDefaults] synchronize]; 

读取数据:

 NSString *imagePath = [[NSUserDefaults standardUserDefaults] objectForKey:kPLDefaultsAvatarUrl]; if (imagePath) { self.avatarImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imagePath]]; } 

documentsPathForFileName:

 - (NSString *)documentsPathForFileName:(NSString *)name { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; return [documentsPath stringByAppendingPathComponent:name]; } 

对于iOS8 / XCODE6正如tmr和DevC在下面的评论中提到的那样,xcode6 / ios8存在一个问题。 xcode5和xcode 6安装过程的不同之处在于xcode6在每次运行xcode之后都会更改应用程序UUID (请参阅path中的高亮部分:/ var / mobile / Containers / Data / Application / B0D49CF5-8FBE-4F14-87AE-FA8C16A678B1 / Documents / image.jpg的)。

所以有两个解决方法:

  1. 跳过这个问题,因为一旦应用程序安装在真实的设备上它永远不会改变UUID(事实上它确实,但它是新的应用程序)
  2. 保存所需文件夹的相对path(在我们的例子中是应用程序的根目录)

这里是代码的快速版本作为奖金(第二种方法):

写数据:

 let imageData = UIImageJPEGRepresentation(image, 1) let relativePath = "image_\(NSDate.timeIntervalSinceReferenceDate()).jpg" let path = self.documentsPathForFileName(relativePath) imageData.writeToFile(path, atomically: true) NSUserDefaults.standardUserDefaults().setObject(relativePath, forKey: "path") NSUserDefaults.standardUserDefaults().synchronize() 

读取数据:

 let possibleOldImagePath = NSUserDefaults.standardUserDefaults().objectForKey("path") as String? if let oldImagePath = possibleOldImagePath { let oldFullPath = self.documentsPathForFileName(oldImagePath) let oldImageData = NSData(contentsOfFile: oldFullPath) // here is your saved image: let oldImage = UIImage(data: oldImageData) } 

documentsPathForFileName:

 func documentsPathForFileName(name: String) -> String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true); let path = paths[0] as String; let fullPath = path.stringByAppendingPathComponent(name) return fullPath } 

要在NSUserDefaults中保存图像:

 [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:key]; 

从NSUserDefaults中检索图像:

 NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:key]; UIImage* image = [UIImage imageWithData:imageData]; 

尽pipe可以将UIImage保存为NSUserDefaults ,但通常不build议这样做,因为这不是保存图像最有效的方法。 更有效的方法是将图像保存在应用程序的Documents Directory

为了这个问题的目的,我附上了你的问题的答案,以及更有效的保存UIImage


NSUserDefaults(不推荐)

保存到NSUserDefaults

这个方法允许你保存任何UIImageNSUserDefaults

 -(void)saveImageToUserDefaults:(UIImage *)image ofType:(NSString *)extension forKey:(NSString *)key { NSData * data; if ([[extension lowercaseString] isEqualToString:@"png"]) { data = UIImagePNGRepresentation(image); } else if ([[extension lowercaseString] isEqualToString:@"jpg"]) { data = UIImageJPEGRepresentation(image, 1.0); } NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:data forKey:key]; [userDefaults synchronize]; } 

这就是你如何称呼它:

 [self saveImageToUserDefaults:image ofType:@"jpg" forKey:@"myImage"]; [[NSUserDefaults standardUserDefaults] synchronize]; 

从NSUserDefaults加载

这个方法允许你从NSUserDefaults加载任何UIImage

 -(UIImage *)loadImageFromUserDefaultsForKey:(NSString *)key { NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults]; return [UIImage imageWithData:[userDefaults objectForKey:key]]; } 

这就是你如何称呼它:

 UIImage * image = [self loadImageFromUserDefaultsForKey:@"myImage"]; 

一个更好的select

保存到文档目录

此方法允许您将任何UIImage保存到应用程序中的Documents Directory

 -(void)saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath { if ([[extension lowercaseString] isEqualToString:@"png"]) { [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil]; } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) { [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil]; } else { NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension); } } 

这就是你如何称呼它:

 NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; [self saveImage:image withFileName:@"Ball" ofType:@"jpg" inDirectory:documentsDirectory]; 

从文档目录加载

此方法允许您从应用程序的Documents Directory加载任何UIImage

 -(UIImage *)loadImageWithFileName:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath { UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, [extension lowercaseString]]]; return result; } 

这就是你如何称呼它:

 NSString * documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; UIImage * image = [self loadImageWithFileName:@"Ball" ofType:@"jpg" inDirectory:documentsDirectory]; 

一个不同的select

将UIImage保存到照片库

此方法允许您将任何UIImage保存到设备的Photo Library ,并调用如下:

 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); 

将多个UIImage保存到照片库

此方法允许您将多个UIImages保存到设备的Photo Library

 -(void)saveImagesToPhotoAlbums:(NSArray *)images { for (int x = 0; x < [images count]; x++) { UIImage * image = [images objectAtIndex:x]; if (image != nil) UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); } } 

这就是你如何称呼它:

 [self saveImagesToPhotoAlbums:images]; 

images是由UIImages组成的NSArray

为迅速2.2

储藏:

 NSUserDefaults.standardUserDefaults().setObject(UIImagePNGRepresentation(chosenImage), forKey: kKeyImage) 

检索:

 if let imageData = NSUserDefaults.standardUserDefaults().objectForKey(kKeyImage), let image = UIImage(data: imageData as! NSData){ // use your image here... } 

是的,在技术上可行

[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:@"foo"];

但不可取,因为plists不适合用于大量二进制数据blob,尤其是User Prefs。 将图像保存到用户文档文件夹并将该对象的引用存储为URL或path会更好。

从苹果文档,

NSUserDefaults类提供了访问常见types(如浮点数,双精度,整数,布尔值和URL)的便捷方法。 一个默认对象必须是一个属性列表,也就是一个实例(或集合的实例组合):NSData,NSString,NSNumber,NSDate,NSArray或NSDictionary。 如果要存储任何其他types的对象,则通常应将其存档以创buildNSData的实例。

你可以像这样保存图像: –

 [[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation([UIImage imageNamed:@"yourimage.gif"])forKey:@"key_for_your_image"]; 

并阅读这样的: –

  NSData* imageData = [[NSUserDefaults standardUserDefaults]objectForKey:@"key_for_your_image"]; UIImage* image = [UIImage imageWithData:imageData]; 

这在技术上是可行的,但这不是可取的。 将图像保存到磁盘。 NSUserDefaults适用于小的设置,而不是大的二进制数据文件。

适用于Swift 3JPG格式

注册默认图像:

 UserDefaults.standard.register(defaults: ["key":UIImageJPEGRepresentation(image, 100)!]) 

保存图片 :

 UserDefaults.standard.set(UIImageJPEGRepresentation(image, 100), forKey: "key") 

加载图像:

 let imageData = UserDefaults.standard.value(forKey: "key") as! Data let imageFromData = UIImage(data: imageData)! 

将图像保存到NSUserDefault:

 NSData *imageData; // create NSData-object from image imageData = UIImagePNGRepresentation([dic objectForKey:[NSString stringWithFormat:@"%d",i]]); // save NSData-object to UserDefaults [[NSUserDefaults standardUserDefaults] setObject:imageData forKey:[NSString stringWithFormat:@"%d",i]]; 

从NSUserDefault加载图像:

 NSData *imageData; // Load NSData-object from NSUserDefault imageData = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"%d",i]]; // get Image from NSData [image setObject:[UIImage imageWithData:imageData] forKey:[NSString stringWithFormat:@"%d",i]]; 

是的,你可以使用。 但由于它是用于存储首选项,所以可以更好地将图像保存到文档文件夹中。

如果需要,你可以在NSUserDefaults有path。

由于这个问题有一个很高的谷歌search索引 – 这里是@ NikitaTook的答案在今天的时代,即Swift 3和4(exception处理)。

注意:这个类是专门为读写JPG格式的图像文件系统而写的。 Userdefaults东西应该在它之外处理。

writeFile接受jpg图像的文件名(带.jpg扩展名)和UIImage本身,如果能够保存,则返回true,否则返回false,如果无法写入图像,则可以存储图像在Userdefaults这将是您的备份计划或只是再试一次。 readFile函数接受图像文件名,并返回一个UIImage ,如果传递给这个函数的图像名称被find,那么它返回该图像,否则它只是从应用程序的资产文件夹返回一个默认的占位符图像(这样可以避免讨厌的崩溃或其他奇怪的行为)。

 import Foundation import UIKit class ReadWriteFileFS{ func writeFile(_ image: UIImage, _ imgName: String) -> Bool{ let imageData = UIImageJPEGRepresentation(image, 1) let relativePath = imgName let path = self.documentsPathForFileName(name: relativePath) do { try imageData?.write(to: path, options: .atomic) } catch { return false } return true } func readFile(_ name: String) -> UIImage{ let fullPath = self.documentsPathForFileName(name: name) var image = UIImage() if FileManager.default.fileExists(atPath: fullPath.path){ image = UIImage(contentsOfFile: fullPath.path)! }else{ image = UIImage(named: "user")! //a default place holder image from apps asset folder } return image } } extension ReadWriteFileFS{ func documentsPathForFileName(name: String) -> URL { let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let path = paths[0] let fullPath = path.appendingPathComponent(name) return fullPath } }