【发布时间】:2010-11-12 03:54:14
【问题描述】:
我在 UITableView 中显示了非常大尺寸的图像,因此我的应用程序在一段时间后崩溃了。现在我想调整图像大小并将其保存到磁盘。有人可以帮我从 NSData/UIImage 调整图像大小并将其保存到磁盘。
我得到了从 UIImage 调整图像大小的代码,因此我在 UIImage 对象中调整了图像大小,如何将其保存到 iphone 沙箱。
谢谢,
【问题讨论】:
我在 UITableView 中显示了非常大尺寸的图像,因此我的应用程序在一段时间后崩溃了。现在我想调整图像大小并将其保存到磁盘。有人可以帮我从 NSData/UIImage 调整图像大小并将其保存到磁盘。
我得到了从 UIImage 调整图像大小的代码,因此我在 UIImage 对象中调整了图像大小,如何将其保存到 iphone 沙箱。
谢谢,
【问题讨论】:
您是在问“我如何编写文件”,对吗?
我猜你可能想写入Library/Caches目录有一点复杂,所以当手机备份时你不保存这些文件。
使用NSHomeDirectory() 获取应用文件夹的根目录,然后附加库/缓存。
您可以使用 NSData 上的方法将 NSData 写入 fs。如果你有 UIImage,你可以通过UIImageJPEGRepresentation() 或UIImagePNGRepresentation 来获取数据。
【讨论】:
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);
【讨论】:
这是保存到 iOS 上 Documents 目录的代码,它来自工作代码。
// 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];
【讨论】:
[NSData dataWithContentsOfFile:] 或[UIImage imageWithContentsOfFile:]