Loading an Image from documents directory

后端 未结 6 1808
温柔的废话
温柔的废话 2020-12-03 13:51

I cant get my Image(.png) to display.

I check that it exists at the path I use, and it does. But no image appears.

Here is what I\'ve been trying:

         


        
相关标签:
6条回答
  • 2020-12-03 14:18

    Try to use

    NSData *imgData = [NSData dataWithContentsOfFile:imgPath];
    UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
    

    or

    NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL fileURLWithPath:imgPath]];
    UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
    
    0 讨论(0)
  • 2020-12-03 14:21

    You need to give proper file url which will be

    NSURL *imgURL = [NSURL fileURLWithPath:imgPath];
    

    then initialize your image with proper imgURL var and finally to add the image to your cell you need to do the following

    [cell.contentView addSubview:imgView];
    

    I hope it may solve your problem.

    0 讨论(0)
  • 2020-12-03 14:24
    imageView.image = [UIImage imageWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Filename"]];
    
    0 讨论(0)
  • 2020-12-03 14:26

    Swift 4

    Code:

    extension FileManager {
        class func getImage(named: String) -> UIImage? {
            let imagePath = getImagePath(named: named)
            return UIImage(contentsOfFile: imagePath)
        }
    
        class func getImagePath(named: String) -> String {
            let fileManager = FileManager.default
            let documentDir = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            return documentDir.appendingPathComponent(named).path
        }
    }
    

    Usage:

    let image = FileManager.getImage(named: "image.png")
    
    0 讨论(0)
  • 2020-12-03 14:27

    Your url is perfect.

    You need to initialise image with following line

    UIImage *thumbNail=[UIImage imageWithContentsOfFile:imagePath];
    

    now do this

    [imgView setImage:thumbNail];
    
    [cell addSubview:imgView];
    
    0 讨论(0)
  • 2020-12-03 14:28

    You should use [NSURL fileURLWithPath:imgPath] instead of [NSURL URLWithString:imgPath]. Image path is not a valid url, it needs a file:// prefix.

    0 讨论(0)
提交回复
热议问题