imageWithContentsOfFile和imageNamed的区别(imageWithContentsOfFile返回低质量图片)

4

曾经,我把所有的图片都放在APP Bundle中。我使用imageNamed函数获取一张图片。后来,我决定在应用启动时将一些图片复制到Document中。因此,我不能再使用imageNamed函数来获取图片了。我改用imageWithContentsOfFile函数来获取图片:

NSString* documentsDirectoryPath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
UIImage* result =[UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", documentsDirectoryPath, fileName, extension]];

然而,imageWithContentsOfFile返回的图像质量低(非常模糊)。 所有我的图像都是128 * 128。 我使用以下代码检测图片的大小:

NSData * imgData = UIImagePNGRepresentation(image);
NSLog(@"size : %d",[imgData length]);

我发现通过 imageNamed 返回的图片大小是使用 imageWithContentsOfFile 的三倍。 我被搞疯了...救救我!非常感谢...

你是如何将图片复制到文档目录的? - Ares
为什么应用程序启动后无法使用imageNamed获取图像? - Javier Quevedo
2个回答

4
UIImage参考文档中,你可以看到imageNamed和imageWithContentsOfFile之间的一些区别。
  • imageWithContentsOfFile不会缓存图像,也不会寻找retina显示版本(@2x.png)。
  • 而imageNamed会缓存图像,并检查是否有@2x版本,在启用retina的设备上加载该版本。

了解这一点,我认为你遇到问题的最合理解释是:你正在使用一台retina设备,并且拥有相同图像的retina版本(@2x)。这就解释了为什么图片会


0

我使用+ (UIImage *)imageWithContentsOfFile:(NSString *)path来从磁盘加载图像而不缓存它们,以减少内存占用。

自iOS 8x以来,这种方法似乎已经改变。为了在每个iOS版本(7x到9x)上保持功能,我在UIImage上使用了这个简单的类别:

#import <UIKit/UIKit.h>

@interface UIImage (ImageNamedNoCache)

+ (UIImage *)imageNamedNoCache:(NSString *)imageName;

@end

和 .m

#import "UIImage+ImageNamedNoCache.h"

#define MAIN_SCREEN                     [UIScreen mainScreen]
#define SYSTEM_VERSION_LESS_THAN(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)

@implementation UIImage (ImageNamedNoCache)

static NSString *bundlePath = nil;

+ (UIImage *)imageNamedNoCache:(NSString *)imageName
{
    if (!bundlePath)
    {
        bundlePath = [[NSBundle mainBundle] bundlePath];
    }

    NSString *imgPath = [bundlePath stringByAppendingPathComponent:imageName];

    if (SYSTEM_VERSION_LESS_THAN(@"8.0"))
    {
        imgPath = [imgPath stringByAppendingFormat:@"@%ldx.png", (long)[MAIN_SCREEN scale]];
    }
    return [UIImage imageWithContentsOfFile:imgPath];
}

@end

希望这能帮到你 ;)

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