我在UITableView中展示非常大尺寸的图像,因此我的应用程序在一段时间后会崩溃。现在我想调整图像大小并将其保存到磁盘上。是否有人能帮助我从NSData / UIImage调整图像大小并将其保存到磁盘上。
我得到了从UIImage调整图像大小的代码,因此结果是我已经在UIImage对象中拥有了调整大小的图像,如何将其保存到iPhone沙盒中。
谢谢,
以下是可用代码,用于将内容保存到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];
NSHomeDirectory()
获取应用程序文件夹的根目录,然后附加Library/Caches即可。UIImageJPEGRepresentation()
或UIImagePNGRepresentation
来获取数据。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);
[NSData dataWithContentsOfFile:]
或者[UIImage imageWithContentsOfFile:]
。 - Liron