8

我有一个类,用于存储有关手机上资产(图像、视频)的信息。

我的班级有ResourceURLString这样的定义

@property NSURL *ResourceURL;

我正在设置属性,同时assets通过电话循环

Item.ResourceURLString = [[asset valueForProperty:ALAssetPropertyURLs] objectForKey:[[asset valueForProperty:ALAssetPropertyRepresentations] objectAtIndex:0]];

当用户单击图像时,我想加载图像。

我拥有的代码是这个

NSData *imageUrl = [NSData dataWithContentsOfURL:[NSURL URLWithString:[CurrentItem.ResourceURL absoluteString]]];    

Img = [UIImage imageWithData:imageUrl];

但是 Image 总是 nil 我已经验证 ResourceURL 属性包含 URL 资产:library://asset/asset.JPG?id=82690321-91C1-4650-8348-F3FD93D14613&ext=JPG

4

5 回答 5

14

您不能以这种方式加载图像。

您需要为此使用ALAssetsLibrary类。

将 assetslibrary 框架添加到您的项目并添加头文件。

使用以下代码加载图像:

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];
于 2013-01-24T08:37:53.323 回答
8

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
    }
}

如果要检索图片的原始大小,请使用PHImageManagerMaximumSize 。但是,如果您想检索更小或特定的大小,可以将PHImageManagerMaximumSize替换为CGSize(width:150, height:150)

于 2016-11-08T08:10:57.480 回答
6

自 iOS 9.0 起ALAssetsLibrary已弃用。从 iOS 8.0 开始,这适用于 PHPhotoLibrary。这是一个小的 UIImage 扩展,Swift 2X。这使用固定的图像尺寸。

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
            }
        }
    }
}

从 UIImagePickerController 委托获取 imageReferenceURL:

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    imageURL = info[UIImagePickerControllerReferenceURL] as? NSURL
}

设置图像

let imageView = UIImageView()
imageView.imageFromAssetURL(imageURL)

可能有我还没有遇到过的效果,经典的就是 UITableViewCell 或者线程问题。我会保持更新,也感谢您的反馈。

于 2016-03-04T13:22:52.997 回答
0

对于斯威夫特 5

fetchAssets(withALAssetURLs)将在未来的版本中删除。因此我们使用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
                }
            })
        }
    }
}

更新

let image = UIImage(data: NSData(contentsOf: imageURL as URL)! as Data)
于 2021-01-31T05:58:22.720 回答
-1
ALAsset *asset = "asset array index"
[tileView.tileImageView setImage:[UIImage imageWithCGImage:[asset thumbnail]]];
于 2013-01-24T11:03:20.760 回答