Load image from bundle with iOS

IosObjective CUiimage

Ios Problem Overview


I added to my project a .bundle folder filled with some images. Is it correct refer to this image directly writing something like ?:

[UIImage imageNamed:@"imageInBundle.png"];

Which is the best method to access and use these images ?

Ios Solutions


Solution 1 - Ios

That is correct, imageNamed: will search your main bundle. Images in your project, even if they are in different groups in your Project Navigator will be in your main bundle and can be accessed directly by name.

Solution 2 - Ios

If that does not work, try

[UIImage imageNamed:@"yourbundlefile.bundle/imageInBundle.png"];

Best

Solution 3 - Ios

Apple has thankfully provided a proper API for this from iOS 8 onwards, imageNamed:inBundle:compatibleWithTraitCollection:.

It's used like so:

[UIImage               imageNamed:@"image-name"
                         inBundle:[NSBundle bundleForClass:self.class]
    compatibleWithTraitCollection:nil]

or in swift:

let image = UIImage(named: "image-name",
                    inBundle: NSBundle(forClass: type(of:self)),
                    compatibleWithTraitCollection: nil)

or in swift 5:

let image = UIImage(named: "image-name",
                    in: Bundle(for: type(of:self)),
                    compatibleWith: nil)

Solution 4 - Ios

  1. If you are working with bundles go to bundle target and set COMBINE_HIDPI_IMAGES to NO. In another case the image will be converted to tiff format.

  2. try this code:

    NSBundle *bundle = [NSBundle bundleWithURL:[[NSBundle mainBundle] URLForResource:@"YourBundle" withExtension:@"bundle"]]; NSString *imagePath = [bundle pathForResource:@"imageInBundle" ofType:@"png"]; UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

Solution 5 - Ios

Swift 3

let myImage = UIImage(named: "nameOfImage", in: Bundle(for: type(of: self)), compatibleWith: nil)

I can't get current bundle so i do this:

Bundle(for: type(of: self))

Solution 6 - Ios

This Method returns image anywhere in the xcode project:=>

+(UIImage*)returnImageFromResourceBundle:(NSString*)nameOfImage
{
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Resource" ofType:@"bundle"];
    NSString *imageString = [[NSBundle bundleWithPath:bundlePath] pathForResource:nameOfImage ofType:@"png"];
    
    UIImage *retrievedImage = [[UIImage alloc] initWithContentsOfFile: imageString];
    return retrievedImage;
}

Solution 7 - Ios

Since I had to figure this out for Swift, thought I would add also....

if let imagePath = NSBundle.mainBundle().pathForImageResource("TestImage.png")     
{
    imageView.image = NSImage(contentsOfFile: imagePath)
}

Where I have TestImage.png in the Supporting Files group inside my bundle.

Solution 8 - Ios

Swift version

@AndrewMackenzie's answer didn't work me. This is what did work

let image = UIImage(named: "imageInBundle.png")
imageView.image = image

My full answer is here.

Solution 9 - Ios

For Swift 3

let prettyImage = UIImage(named: "prettyImage",
            in: Bundle(for: self),
            compatibleWith: nil)

Solution 10 - Ios

A quick way to do it if you are going to use it a couple of times in the same viewController:

Get the image anywhere in the same class as the method below:

// this fetches the image from: MyBundle.bundle/folder/to/images/myImage.png
UIImage *myImage = [self imageFromBundle:@"MyBundle" withPath:@"folder/to/images/myImage.png"];

Method that fetches the image:

- (UIImage *)imageFromBundle:(NSString *)bundleName withPath:(NSString *)imageName
{
    NSURL *bundleURL = [[NSBundle mainBundle] URLForResource:bundleName withExtension:@"bundle"];
    NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
    NSString *imagePath = [bundle pathForResource:imageName ofType:nil];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}

Or simply call it straight out of the bundle:

UIImage *myImage = [UIImage imageNamed:@"MyBundle.bundle/folder/to/images/myImage.png"];

Solution 11 - Ios

If you are building a framework and you would like all instances of UIImage(named: "image") to always use your custom bundle, you can make an extension like below that will override it

// Swift 5

extension UIImage {
  convenience init?(named: String) {
    self.init(named: named, in: <#Your Bundle#>, compatibleWith: nil)
  }
}

Solution 12 - Ios

This is worked for me in Swift 5

// Empty UIImage array to store the images in it.
var icons = [UIImage]()

let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("MyBundle.bundle") // Bundle URL
do {
  let contents = try fileManager.contentsOfDirectory(at: assetURL,
 includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey],
 options: .skipsHiddenFiles)
  for item in contents { // item is the URL of everything in MyBundle imgs or otherwise.

      let image = UIImage(contentsOfFile: item.path) // Initializing an image
      icons.append(image!) // Adding the image to the icons array
  }
}
catch let error as NSError {
  print(error)
}

Solution 13 - Ios

I found this question when trying to solve loading images from Swift Package, so if anybode else is struggling with that as well here's how I solved it:

let image = UIImage(named: "imageName", in: Bundle.module, compatibleWith: nil)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatterGoalView Question on Stackoverflow
Solution 1 - IosJoeView Answer on Stackoverflow
Solution 2 - IosIgnacio PascualView Answer on Stackoverflow
Solution 3 - IosJosephHView Answer on Stackoverflow
Solution 4 - Iosuser1794139View Answer on Stackoverflow
Solution 5 - IososcarrView Answer on Stackoverflow
Solution 6 - IosMohammad AsifView Answer on Stackoverflow
Solution 7 - IosAndrew MackenzieView Answer on Stackoverflow
Solution 8 - IosSuragchView Answer on Stackoverflow
Solution 9 - IosPavle MijatovicView Answer on Stackoverflow
Solution 10 - IosemotalityView Answer on Stackoverflow
Solution 11 - IosFonixView Answer on Stackoverflow
Solution 12 - IosHassan ElDesoukyView Answer on Stackoverflow
Solution 13 - IosKent RobinView Answer on Stackoverflow