JPG image doesn't load with UIImage imageNamed

倾然丶 夕夏残阳落幕 提交于 2019-11-29 03:05:43
Jason Cross

The latest developer reference states the missing piece of information:

Special Considerations On iOS 4 and later, if the file is in PNG format, it is not necessary to specify the .PNG filename extension. Prior to iOS 4, you must specify the filename extension.

One possible reason that the library gives PNGs special treatment, is that the iOS hardware is optimized for PNGs. PNG images stored in the application bundle are optimized by Xcode, changing the byte order of the PNG images to match the graphics chip of the iPhone device. (see this question: Is PNG preferred over JPEG for all image files on iOS?).

If you know that you will only have a PNG or a JPG, an alternative solution is to create a category on UIImage as per below.

- (UIImage*) jgcLoadPNGorJPGImageWithName:(NSString*)name {
    UIImage * value;
    if (nil != name) {
        value = [UIImage imageNamed:name];
        if (nil == value) {
            NSString * jpgName = [NSString stringWithFormat:@"%@.jpg", name];
            value = [UIImage imageNamed:jpgName];
        }
    }
    return value;
}
Beau Nouvelle

If you have these images bundled in your app, you SHOULD know their extensions.

If you're getting them from an online source and you have them as NSData, you can use this code here to determine the type.

+ (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];

    switch (c) {
    case 0xFF:
        return @"image/jpeg";
    case 0x89:
        return @"image/png";
    case 0x47:
        return @"image/gif";
    case 0x49:
    case 0x4D:
        return @"image/tiff";
    }
    return nil;
}

As per the top answer in this question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!