【问题标题】:Save Image to sandbox from UIImage in iPhone将图像从 iPhone 中的 UIImage 保存到沙箱
【发布时间】:2010-11-12 03:54:14
【问题描述】:

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

我得到了从 UIImage 调整图像大小的代码,因此我在 UIImage 对象中调整了图像大小,如何将其保存到 iphone 沙箱。

谢谢,

【问题讨论】:

    标签: iphone uiimage


    【解决方案1】:

    您是在问“我如何编写文件”,对吗?

    我猜你可能想写入Library/Caches目录有一点复杂,所以当手机备份时你不保存这些文件。

    使用NSHomeDirectory() 获取应用文件夹的根目录,然后附加库/缓存。

    您可以使用 NSData 上的方法将 NSData 写入 fs。如果你有 UIImage,你可以通过UIImageJPEGRepresentation()UIImagePNGRepresentation 来获取数据。

    【讨论】:

    • 你可能想使用 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); NSString *cachesDirectory = [paths objectAtIndex:0];而不是自己附加“库/缓存”。
    【解决方案2】:

    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);

    【讨论】:

      【解决方案3】:

      这是保存到 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]; 
      

      【讨论】:

      • 很棒的答案,它帮助了我。再次访问该数据是否简单(一行代码)?还是我应该在堆栈上问另一个问题?
      • @KKendall 你可以做[NSData dataWithContentsOfFile:][UIImage imageWithContentsOfFile:]
      • JPEG 是一种有损格式,因此我建议改用 UIImagePNGRepresentation。如果您反复向磁盘写入/读取图像,则会出现质量问题。
      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 2011-01-16
      • 2012-02-14
      • 2023-02-03
      • 2011-04-14
      • 2010-11-04
      • 1970-01-01
      相关资源
      最近更新 更多