Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPG image doesn't load with UIImage imageNamed

Tags:

I read on the reference that from iOS version 4.+ with the method imageNamed of UIImage object, the file extension is not required.

From UIImage class reference:

Special Considerations.

On iOS 4 and later, the name of the file is not required to specify the filename extension. Prior to iOS 4, you must specify the filename extension.

But it seems that this only work with PNG files.

If my code is:

[UIImage imageNamed:@"test"];
  • The image loads only if the file is test.png
  • The image doesn't load if it's test.jpg.

For me it is a big problem because I need to maintain a dynamic image loading (I do not know at runtime if the image I want to load is png or jpg).

Please can you help me?
Thanks.

like image 836
Rasmas Avatar asked Aug 22 '11 14:08

Rasmas


People also ask

How do I add an image to UIImage?

With Interface Builder it's pretty easy to add and configure a UIImageView. The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project).

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage . Save this answer.

How do I find my UIImage path?

if you already have the image i.e. have added the file to your resources, you can use this to get the file path; NSString *string = [[NSBundle mainBundle] pathForResource:@"IMAGE_FILE_NAME" ofType:@"jpg"]; // or ofType:@"png", etc. Save this answer.

What is UIImage?

An object that manages image data in your app.


1 Answers

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;
}
like image 54
Jason Cross Avatar answered Sep 18 '22 07:09

Jason Cross