将UIImage保存到iPhone的沙盒中

12

我在UITableView中展示非常大尺寸的图像,因此我的应用程序在一段时间后会崩溃。现在我想调整图像大小并将其保存到磁盘上。是否有人能帮助我从NSData / UIImage调整图像大小并将其保存到磁盘上。

我得到了从UIImage调整图像大小的代码,因此结果是我已经在UIImage对象中拥有了调整大小的图像,如何将其保存到iPhone沙盒中。

谢谢,

3个回答

30

以下是可用代码,用于将内容保存到iOS上的“文档”目录。

// Convert UIImage to JPEG
NSData *imgData = UIImageJPEGRepresentation(image, 1); // 1 is compression quality

// Identify the home directory and file name    
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"]; 

// Write the file.  Choose YES atomically to enforce an all or none write. Use the NO flag if partially written files are okay which can occur in cases of corruption
[imgData writeToFile:jpgPath atomically:YES]; 

很棒的答案,它帮助了我。再次访问那些数据是否简单(只需一行代码)?还是我应该在Stack上提出另一个问题? - SirRupertIII
1
@KKendall 你可以直接使用 [NSData dataWithContentsOfFile:] 或者 [UIImage imageWithContentsOfFile:] - Liron
1
JPEG是一种有损格式,因此我建议使用UIImagePNGRepresentation。如果您反复将图像写入/从磁盘读取,则会出现质量问题。 - user1021430

4
你正在询问“如何编写文件”,对吧?
我想这里稍微有些复杂,因为你可能想要写入到Library/Caches目录中,这样当手机备份时就不会保存这些文件。
使用NSHomeDirectory()获取应用程序文件夹的根目录,然后附加Library/Caches即可。
你可以使用NSData的方法将NSData写入文件系统。如果你有一个UIImage,则可以使用UIImageJPEGRepresentation()UIImagePNGRepresentation来获取数据。

6
你可能想使用以下代码: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDirectory = [paths objectAtIndex:0];而不是自己添加“Library/Caches”。 - Jesse Rusak

1

NSData *imgData = UIImageJPEGRepresentation(image, 1);

NSData *imgData = UIImageJPEGRepresentation(image,1);

CGImageSourceRef source = CGImageSourceCreateWithData((CFMutableDataRef)imgData, NULL);
NSDictionary *metadata = [(NSDictionary *) CGImageSourceCopyPropertiesAtIndex(source,0,NULL)autorelease];
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
[imageMutableData writeToFile:jpgPath atomically:YES];

它将把您的图像复制到沙盒中的文档文件夹,并命名为Test.jpg

如果您想对PNG进行操作,可以尝试UIImagePNGRepresentation(image);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接