来自文件的 UIImage 始终为零

UIImage from file always nil

我正在制作文档扫描应用程序

扫描的文档存储在应用程序结构中的临时文件中,该文件的路径存储在 NSString 变量中

此图像被传递到成功加载的 UIImageView

[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];

然后想把图片转成base64准备上传。为了做到这一点,我将调用以下接受 UIImage 对象的方法

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

imageFilePath 变量的值为

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

从我使用的文件中获取图像

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

base64String   = [self encodeToBase64String:img];

问题在于 UIImage 对象始终为 nill(或 nill)。起初我认为问题可能出在路径上,但图像加载在 UIImageView 中。

有人可以帮我弄清楚为什么这不 return 存储在 imageFilePath 变量中的图像

替换:

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

与:

UIImage *img = [UIImage imageWithContentsOfFile:imageFilePath];

您没有从包中加载图像。

此外,请确保您没有尝试在应用的执行过程中使用完整路径。仅保留相对路径,因为应用沙箱的路径会随时间变化。