ios 如何获取通过 iphone 照片库选择的图像名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4314405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i get the name of image picked through photo library in iphone?
提问by Sandeep Singh
I am picking an image from photo library in iphone application. How will i retrieve the actual image name.
我正在从 iphone 应用程序的照片库中挑选一张图片。我将如何检索实际图像名称。
in .h class
在 .h 类中
UIImageView * imageView;
UIButton * choosePhotoBtn;
in .m class
在 .m 班
-(IBAction) getPhoto:(id) sender
{
UIImagePickerController * picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
if((UIButton *) sender == choosePhotoBtn)
{
picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
}
else
{
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
}
[self presentModalViewController:picker animated:YES];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
[picker dismissModalViewControllerAnimated:YES];
imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}
How will i get the actual name of image ?
我将如何获得图像的实际名称?
I m new in iphone. Please help me.
我是 iphone 新手。请帮我。
Thanks in advance.
提前致谢。
回答by Joanne
import AssetsLibrary in your file:
在您的文件中导入 AssetsLibrary:
#import <AssetsLibrary/AssetsLibrary.h>
And, in - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
而且,在 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
put
放
// get the ref url
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
// define the block to call when we get the asset based on the url (below)
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
{
ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
NSLog(@"[imageRep filename] : %@", [imageRep filename]);
};
// get the asset library and fetch the asset based on the ref url (pass in block above)
ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];
so you'll get the image name in log.
所以你会在日志中得到图像名称。
*don't forget to add existing framework: AssetsLibrary.framework Steps:
*不要忘记添加现有框架:AssetsLibrary.framework 步骤:
- In the project navigator, select your project
- Select your target
- Select the 'Build Phases' tab
- Open 'Link Binaries With Libraries' expander
- Click the '+' button
- Select your framework
- (optional) Drag and drop the added framework to the 'Frameworks' group
- 在项目导航器中,选择您的项目
- 选择你的目标
- 选择“构建阶段”选项卡
- 打开“使用库链接二进制文件”扩展器
- 单击“+”按钮
- 选择您的框架
- (可选)将添加的框架拖放到“框架”组
Source: http://www.raywenderlich.com/forums/viewtopic.php?f=2&p=34901& How to "add existing frameworks" in Xcode 4?
来源: http: //www.raywenderlich.com/forums/viewtopic.php?f=2&p=34901& 如何在 Xcode 4 中“添加现有框架”?
回答by parag
If you are building for iOS 9+ target, you will see a bunch of deprecation warnings with ALAssetsLibrary, i.e.:
如果你正在为 iOS 9+ 目标构建,你会看到一堆 ALAssetsLibrary 的弃用警告,即:
'assetForURL(_:resultBlock:failureBlock:)' was deprecated in iOS 9.0: Use fetchAssetsWithLocalIdentifiers:options: on PHAsset to fetch assets by local identifier (or to lookup PHAssets by a previously known ALAssetPropertyAssetURL use fetchAssetsWithALAssetURLs:options:) from the Photos framework instead
'assetForURL(_:resultBlock:failureBlock:)' 在 iOS 9.0 中被弃用:使用 fetchAssetsWithLocalIdentifiers:options: on PHAsset 通过本地标识符获取资产(或通过先前已知的 ALAssetPropertyAssetURL 查找 PHAssets 使用 fetchAssetsWithALAssetURLs from the Photosoptions:反而
As the warning describes, you should use PHAsset. Using swift 2.x, for example, you will need to add import Photos
to your file first. Then, in the didFinishPickingMediaWithInfo
UIImagePickerControllerDelegate method use fetchAssetsWithALAssetURLs
to get the filename:
正如警告所述,您应该使用 PHAsset。例如,使用 swift 2.x,您需要先添加import Photos
到您的文件中。然后,在didFinishPickingMediaWithInfo
UIImagePickerControllerDelegate 方法中使用fetchAssetsWithALAssetURLs
获取文件名:
if let imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL {
let result = PHAsset.fetchAssetsWithALAssetURLs([imageURL], options: nil)
let filename = result.firstObject?.filename ?? ""
}
This will set filename
to be something like, "IMG_0007.JPG".
这将设置filename
为类似“IMG_0007.JPG”的内容。
回答by Bart?omiej Semańczyk
Simple Swift implementation:
简单的 Swift 实现:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL {
ALAssetsLibrary().assetForURL(referenceUrl, resultBlock: { asset in
let fileName = asset.defaultRepresentation().filename()
//do whatever with your file name
}, failureBlock: nil)
}
}
}
Remember about: import AssetsLibrary
请记住: import AssetsLibrary
回答by Heiko Hoffmann
In Objective C, use the Photos framework and import Photos/Photos.h
在Objective C中,使用Photos框架并导入Photos/Photos.h
Then, in your imagePickerController function add the following to get the filename of the image from the photo library
然后,在您的 imagePickerController 函数中添加以下内容以从照片库中获取图像的文件名
NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[refURL] options:nil];
NSString *filename = [[result firstObject] filename];
回答by Shyam Bhat
Though you may be able to retrieve the last path component and use it like a file name, it is not advisable to do so. These filenames are assigned by the system for iTunes to understand while syncing and are not meant for programmers to access as they could be replaced by some other images in future syncs.
尽管您可以检索最后一个路径组件并将其用作文件名,但不建议这样做。这些文件名由系统分配,供 iTunes 在同步时理解,不供程序员访问,因为它们可能会在将来的同步中被其他一些图像替换。
A good round about for this is to assign the current Date as filenames, while saving to images picked from the gallery. You may save it in your documents or library directory and use a mapping PList file to map images to their filename.
一个很好的方法是将当前日期指定为文件名,同时保存到从图库中挑选的图像。您可以将其保存在您的文档或库目录中,并使用映射 PList 文件将图像映射到其文件名。
Alternatively, you can also assign unique numbers as filenames and access the images using these values.
或者,您也可以指定唯一编号作为文件名并使用这些值访问图像。
回答by Ispas Claudiu
Objective Cimplementation that works on iOS 10. ALAssetsLibrary seems to be deprecated so you should use PHAsset:
适用于iOS 10 的Objective C实现。ALAssetsLibrary 似乎已被弃用,因此您应该使用 PHAsset:
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
PHAsset *phAsset = [[PHAsset fetchAssetsWithALAssetURLs:@[imageURL] options:nil] lastObject];
NSString *imageName = [phAsset valueForKey:@"filename"];
UIImage *photo = [info valueForKey:UIImagePickerControllerOriginalImage];
NSLog(@"Picked image: %@ width: %f x height: %f",imageName, photo.size.width, photo.size.height);
[picker dismissViewControllerAnimated:YES completion:nil];
}
回答by Sami Yousif
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
let imageUrl = info[UIImagePickerControllerReferenceURL] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
self.dismiss(animated: true, completion: nil);
}
回答by Kiran S
var fileName: String = "Attachment"
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let assets = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let assetResource = PHAssetResource.assetResources(for: assets.firstObject!)
fileName = assetResource.first?.originalFilename ?? "Attachment"
}
print(fileName)
回答by Vitalii
As of Swift 3 and iOS8+the .filename is not accessible any more. It is still available through self.valueForKey("filename"), but not quite legal though.
从Swift 3 和 iOS8+ 开始,.filename 不再可访问。它仍然可以通过 self.valueForKey("filename") 获得,但并不完全合法。
However, I found this answerin the question "iOS8 Photos Framework: How to get the name(or filename) of a PHAsset?"to be short, simple, and legal.
但是,我在问题“iOS8 照片框架:如何获取 PHAsset 的名称(或文件名)?”中找到了这个答案。简短、简单且合法。