PowerMan2015
PowerMan2015

Reputation: 1418

UIImage from file always nil

I am making a document scanning app

the document that is scanned is stored in a temp file within the application structure and the path of this file stored in a NSString variable

This image is passed to a UIImageView which successfully loads

[self.cameraViewController captureImageWithCompletionHander:^(NSString *imageFilePath)
{
    UIImageView *captureImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:imageFilePath]];
    captureImageView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.7];
    captureImageView.frame = CGRectOffset(weakSelf.view.bounds, 0, -weakSelf.view.bounds.size.height);
    captureImageView.alpha = 1.0;
    captureImageView.contentMode = UIViewContentModeScaleAspectFit;
    captureImageView.userInteractionEnabled = YES;
    [weakSelf.view addSubview:captureImageView];

Then want to convert the image to base64 ready for upload. In order to do this i will call the following which accepts a UIImage object

- (NSString *)encodeToBase64String:(UIImage *)image {
    return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}

The value of the imageFilePath variable is

/private/var/mobile/Containers/Data/Application/79C28B96-275D-48F1-B701-CABD699C388D/tmp/ipdf_img_1447880304.jpeg

To fetch the image from the file i used this

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageFilePath ofType:nil]];

base64String   = [self encodeToBase64String:img];

The problem is that the UIImage object is always nill (or nill). At first i though that the problem could be the path, but the image loads within the UIImageView.

Can someone please help me with the figuring out why this does not return the image stored within the imageFilePath variable

Upvotes: 0

Views: 615

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Replace:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:imageFilePath ofType:nil]];

with:

UIImage *img = [UIImage imageWithContentsOfFile:imageFilePath];

You are not loading the image from the bundle.

Also, make sure you are not trying to use the full path across executions of the app. Only persist relative paths since the path to the app's sandbox can change over time.

Upvotes: 1

Related Questions