[英]Unable to load image from asset URL
I have a class that stores information about the assets on the phone (images, videos).我有一个存储有关手机上资产信息的类(图像、视频)。
My class has the ResourceURLString
defined as such我的班级有这样定义的ResourceURLString
@property NSURL *ResourceURL;
I am setting the property while looping trough the assets
on the phone as such我在通过电话上的assets
循环时设置属性
Item.ResourceURLString = [[asset valueForProperty:ALAssetPropertyURLs] objectForKey:[[asset valueForProperty:ALAssetPropertyRepresentations] objectAtIndex:0]];
When the user clicks on an image I want to load the image.当用户单击图像时,我想加载图像。
The code that I have is this我的代码是这样的
NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:[CurrentItem.ResourceURL absoluteString]]];
Img = [UIImage imageWithData:imageUrl];
But the Image is always nil I have verified that the ResourceURL property contains the URL assets: library://asset/asset.JPG?id=82690321-91C1-4650-8348-F3FD93D14613&ext=JPG
但图像始终为零我已验证 ResourceURL 属性包含 URL 资产: library://asset/asset.JPG?id=82690321-91C1-4650-8348-F3FD93D14613&ext=JPG
You can't load images in this way.您不能以这种方式加载图像。
You need to use ALAssetsLibrary
class for this. ALAssetsLibrary
您需要使用ALAssetsLibrary
类。
Add assetslibrary framework to your project and add header files.将 assetslibrary 框架添加到您的项目并添加头文件。
Use the below code for loading image:使用以下代码加载图像:
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
{
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref) {
UIImage *largeimage = [UIImage imageWithCGImage:iref];
yourImageView.image = largeImage;
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror)
{
NSLog(@"Can't get image - %@",[myerror localizedDescription]);
};
NSURL *asseturl = [NSURL URLWithString:yourURL];
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:asseturl
resultBlock:resultblock
failureBlock:failureblock];
Since iOS 8 you can use the Photos Framework here is how to do it in Swift 3从iOS 8 开始,您可以在此处使用照片框架,这是在Swift 3 中的操作方法
import Photos // use the Photos Framework
// declare your asset url
let assetUrl = URL(string: "assets-library://asset/asset.JPG?id=9F983DBA-EC35-42B8-8773-B597CF782EDD&ext=JPG")!
// retrieve the list of matching results for your asset url
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [assetUrl], options: nil)
if let photo = fetchResult.firstObject {
// retrieve the image for the first result
PHImageManager.default().requestImage(for: photo, targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: nil) {
image, info in
let myImage = image //here is the image
}
}
Use PHImageManagerMaximumSize if you want to retrieve the original size of the picture.如果要检索图片的原始大小,请使用PHImageManagerMaximumSize 。 But if you want to retrieve a smaller or specific size you can replace PHImageManagerMaximumSize by CGSize(width:150, height:150)
但是如果你想检索一个更小的或特定的尺寸,你可以用CGSize(width:150, height:150)
替换PHImageManagerMaximumSize
As of iOS 9.0 ALAssetsLibrary
is deprecated.从 iOS 9.0 ALAssetsLibrary
,不推荐使用ALAssetsLibrary
。 Since iOS 8.0, this works with the PHPhotoLibrary.从 iOS 8.0 开始,这适用于 PHPhotoLibrary。 This is a small UIImage extension, Swift 2X.这是一个小的 UIImage 扩展,Swift 2X。 This uses a fixed image size.这使用固定的图像大小。
import Photos
extension UIImageView {
func imageFromAssetURL(assetURL: NSURL) {
let asset = PHAsset.fetchAssetsWithALAssetURLs([assetURL], options: nil)
guard let result = asset.firstObject where result is PHAsset else {
return
}
let imageManager = PHImageManager.defaultManager()
imageManager.requestImageForAsset(result as! PHAsset, targetSize: CGSize(width: 200, height: 200), contentMode: PHImageContentMode.AspectFill, options: nil) { (image, dict) -> Void in
if let image = image {
self.image = image
}
}
}
}
Getting the imageReferenceURL from the UIImagePickerController delegate:从 UIImagePickerController 委托获取 imageReferenceURL:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL
}
Setting the image设置图像
let imageView = UIImageView()
imageView.imageFromAssetURL(imageURL)
There might be effects I haven't encountered yet, a classic would be UITableViewCell or thread problems.可能有我还没有遇到过的效果,经典的就是 UITableViewCell 或线程问题。 I'll keep this updated, also appreciate your feedback.我会保持更新,也感谢您的反馈。
For Swift 5对于 Swift 5
fetchAssets(withALAssetURLs)
will be removed in a future release. fetchAssets(withALAssetURLs)
将在未来版本中移除。 Hence we using fetchAssets
to get image from asset local identifier因此我们使用fetchAssets
从资产本地标识符中获取图像
extension UIImageView {
func imageFromLocalIdentifier(localIdentifier: String, targetSize: CGSize) {
let fetchOptions = PHFetchOptions()
// sort by date desending
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// fetch photo with localIdentifier
let results = PHAsset.fetchAssets(withLocalIdentifiers: [localIdentifier], options: fetchOptions)
let manager = PHImageManager.default()
results.enumerateObjects { (thisAsset, _, _) in
manager.requestImage(for: thisAsset, targetSize: targetSize, contentMode: .aspectFit, options: nil, resultHandler: {(image, _) in
DispatchQueue.main.async {[weak self] in
self?.image = image
}
})
}
}
}
Update更新
let image = UIImage(data: NSData(contentsOf: imageURL as URL)! as Data)
ALAsset *asset = "asset array index"
[tileView.tileImageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.