加载图像到ImageView的,采取从文件路径
问题描述:
- (IBAction)chooseImgBtnClick:(id)sender {
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.allowsEditing = YES;
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
[self presentViewController:picker animated:YES completion:NULL];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
_image=[info objectForKey:UIImagePickerControllerOriginalImage];
[_vehicleImageView setImage:_image];
[self dismissViewControllerAnimated:YES completion:NULL];_vehicleImageView.image= [info objectForKey:@"UIImagePickerControllerOriginalImage"];
NSData *webData = UIImagePNGRepresentation(_vehicleImageView.image);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"png"];
[webData writeToFile:localFilePath atomically:YES];
NSLog(@"localFilePath.%@",localFilePath);
_filePath=localFilePath;
}
影像使用我选择从库中的照片,上面的代码,并设置在UIImageView的照片并试图采取的路径到一个名为localFilePath字符串。我将路径分配给_filepath。加载图像到ImageView的,采取从文件路径
现在我编写了一个函数,用于从文件路径中获取图像,并在单击另一个按钮时将图像载入另一个UIImageView。 但图像没有被加载。请告知
以下是功能。
- (IBAction)loadSecondView:(id)sender {
NSData *pngData = [NSData dataWithContentsOfFile:_filePath];
UIImage *image = [UIImage imageWithData:pngData];
[_secondImageView setImage:image];
}
答
我没有将图像名称保存到属性中。之后,我使用下面的代码从特定路径中取回图像并放入ImageView中。
-(UIImage*) getImage:(NSString *) imageName{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString* path = [documentsDirectory stringByAppendingPathComponent:
imageName ];
UIImage* image = [UIImage imageWithContentsOfFile:path];
NSLog(@"%@",image);
return image;
}
答
的iOS,而越来越接近向有网友认为的“文件”和“目录”,并不完全启用。我认为最终你有两种选择可供选择。我将按照可用性从大到小的顺序列出它们:
(1)使用OS“原样” - 相机,相机胶卷,照片库。这可能需要重构一些你正在做的事情,但这也是“iOS方式”。
(2)与iCloud Drive and the Document Picker一起使用。这个链接是一个高层次的解释。使用这个你可以获得更多的“苹果方式”,但是你现在限制用户在iCloud中存储东西。
(3)利用名为Document Provider的应用程序扩展。我从来没有使用这个(但),但我相信这将在“云”中进一步扩展事物,并让您能够读/写Dropbox等。谨慎的一句话:我已经使用了Photo Editing在一个应用程序中扩展,并且有不少“陷阱”,你必须忍受。扩展在UI方面比应用程序更受限制。 (4)我不知道这是否可行,但如果你真的陷入困境,也许你可以使用某种形式的“深层链接”来让你的应用成为打开某些图像的默认应用。这是一个长镜头 - 虽然我真的不认为它会工作。
只有三个sourceTypes可用,其中一个是相机。除非你想要相机胶卷(sourceType == savedPhotosAlbum),否则很难知道你正在寻找什么,没有一个更详细的例子。 iOS设备上的“任何目录”要么不明确(你的意思是iCloud还是其他地方的“off-device”?)或不可能的(iOS设备没有目录概念)。请给予更多的细节.... – dfd
我同意@dfd。请阅读这里的答案: - http://stackoverflow.com/a/1082265/4525734 此外,这是链接到苹果文档: https://developer.apple.com/reference/uikit/uiimagepickercontrollersourcetype –
是不可能从文档文件夹中选择图像或者在项目中创建的具有一些图像的任何文件夹? – Harish