我可以从URL加载UIImage吗?

问题描述 投票:127回答:11

我有一个图像的URL(从UIImagePickerController获取)但我不再拥有内存中的图像(该URL是从以前的应用程序运行中保存的)。我可以再次从URL重新加载UIImage吗?

我看到UIImage有一个imageWithContentsOfFile:但我有一个URL。我可以使用NSData的dataWithContentsOfURL:来读取URL吗?

EDIT1


根据@ Daniel的回答,我尝试了以下代码,但它不起作用......

NSLog(@"%s %@", __PRETTY_FUNCTION__, photoURL);     
if (photoURL) {
    NSURL* aURL = [NSURL URLWithString:photoURL];
    NSData* data = [[NSData alloc] initWithContentsOfURL:aURL];
    self.photoImage = [UIImage imageWithData:data];
    [data release];
}

当我运行它时控制台显示:

-[PhotoBox willMoveToWindow:] file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG
*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSURL length]: unrecognized selector sent to instance 0x536fbe0'

查看调用堆栈,我调用URLWithString,调用URLWithString:relativeToURL:,然后是initWithString:relativeToURL:,然后是_CFStringIsLegalURLString,然后是CFStringGetLength,然后是forwarding_prep_0,然后转发,然后调用 - [NSObject doesNotRecognizeSelector]。

我的NSString(photoURL的地址是0x536fbe0)没有响应长度的任何想法?为什么它说它没有响应 - [NSURL长度]?难道不知道param是NSString,而不是NSURL吗?

我懂了


好的,代码的唯一问题是字符串到URL的转换。如果我硬编码字符串,其他一切工作正常。所以我的NSString有问题,如果我无法弄清楚,我想这应该是一个不同的问题。插入此行(我从上面的控制台日志粘贴路径),它工作正常:

photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";
ios iphone uiimage uiimagepickercontroller
11个回答
314
投票

你可以这样做(同步,但紧凑):

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];

更好的方法是使用Apple的LazyTableImages来保持交互性。


2
投票

使用Swift ExtensionUIImageView的方式(源代码here):

为关联的UIActivityIndicatorView创建计算属性

import Foundation
import UIKit
import ObjectiveC

private var activityIndicatorAssociationKey: UInt8 = 0

extension UIImageView {
    //Associated Object as Computed Property
    var activityIndicator: UIActivityIndicatorView! {
        get {
            return objc_getAssociatedObject(self, &activityIndicatorAssociationKey) as? UIActivityIndicatorView
        }
        set(newValue) {
            objc_setAssociatedObject(self, &activityIndicatorAssociationKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
        }
    }

    private func ensureActivityIndicatorIsAnimating() {
        if (self.activityIndicator == nil) {
            self.activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
            self.activityIndicator.hidesWhenStopped = true
            let size = self.frame.size;
            self.activityIndicator.center = CGPoint(x: size.width/2, y: size.height/2);
            NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                self.addSubview(self.activityIndicator)
                self.activityIndicator.startAnimating()
            })
        }
    }

自定义初始化程序和设置程序

    convenience init(URL: NSURL, errorImage: UIImage? = nil) {
        self.init()
        self.setImageFromURL(URL)
    }

    func setImageFromURL(URL: NSURL, errorImage: UIImage? = nil) {
        self.ensureActivityIndicatorIsAnimating()
        let downloadTask = NSURLSession.sharedSession().dataTaskWithURL(URL) {(data, response, error) in
            if (error == nil) {
                NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                    self.activityIndicator.stopAnimating()
                    self.image = UIImage(data: data)
                })
            }
            else {
                self.image = errorImage
            }
        }
        downloadTask.resume()
    }
}

0
投票

通过Url加载图像的最佳和简单方法是本规范:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData *data =[NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];

    dispatch_async(dispatch_get_main_queue(), ^{
        imgView.image= [UIImage imageWithData:data];
    });
});

用你的imgUrl替换ImageURL 用你的imgView替换UIImageView

它会将Image加载到另一个Thread中,因此它不会减慢App负载。


28
投票

你可以尝试SDWebImage,它提供:

  1. 异步加载
  2. 缓存供离线使用
  3. 放置支架图像以在加载时显示
  4. 适用于UITableView

快速举例:

    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

7
投票

获取DLImageLoader并尝试以下代码

   [DLImageLoader loadImageFromURL:imageURL
                          completed:^(NSError *error, NSData *imgData) {
                              imageView.image = [UIImage imageWithData:imgData];
                              [imageView setContentMode:UIViewContentModeCenter];

                          }];

使用DLImageLoader的另一个典型的现实例子,它可以帮助某人...

PFObject *aFacebookUser = [self.fbFriends objectAtIndex:thisRow];
NSString *facebookImageURL = [NSString stringWithFormat:
    @"http://graph.facebook.com/%@/picture?type=large",
    [aFacebookUser objectForKey:@"id"] ];

__weak UIImageView *loadMe = self.userSmallAvatarImage;
// ~~note~~ you my, but usually DO NOT, want a weak ref
[DLImageLoader loadImageFromURL:facebookImageURL
   completed:^(NSError *error, NSData *imgData)
    {
    if ( loadMe == nil ) return;

    if (error == nil)
        {
        UIImage *image = [UIImage imageWithData:imgData];
        image = [image ourImageScaler];
        loadMe.image = image;
        }
    else
        {
        // an error when loading the image from the net
        }
    }];

正如我上面提到的那样,Haneke是另一个值得考虑的重要图书馆(不幸的是它不是轻量级的)。


6
投票

而迅捷的版本:

   let url = NSURL.URLWithString("http://live-wallpaper.net/iphone/img/app/i/p/iphone-4s-wallpapers-mobile-backgrounds-dark_2466f886de3472ef1fa968033f1da3e1_raw_1087fae1932cec8837695934b7eb1250_raw.jpg");
    var err: NSError?
    var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
    var bgImage = UIImage(data:imageData)

6
投票

如果你真的,绝对肯定NSURL是一个文件网址,即[url isFileURL]保证在你的情况下返回true,那么你可以简单地使用:

[UIImage imageWithContentsOfFile:url.path]

5
投票

尝试使用此代码,您可以使用它设置加载图像,以便用户知道您的应用正在从网址加载图片:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
    [yourImageView setContentMode:UIViewContentModeScaleAspectFit];

    //Request image data from the URL:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData)
            {
                //Load the data into an UIImage:
                UIImage *image = [UIImage imageWithData:imgData];

                //Check if your image loaded successfully:
                if (image)
                {
                    yourImageView.image = image;
                }
                else
                {
                    //Failed to load the data into an UIImage:
                    yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
                }
            }
            else
            {
                //Failed to get the image data:
                yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
            }
        });
    });

4
投票

查看AsyncImageView提供的here。一些很好的示例代码,甚至可以为您提供“开箱即用”。


4
投票

AFNetworking通过占位符支持将异步图像加载到UIImageView中。它还支持异步网络,以便与API一起使用。


3
投票

确保从iOS 9启用此设置:

Info.plist中的应用程序传输安全设置,以确保从URL加载图像,以便它允许下载图像并进行设置。

enter image description here

并写下这段代码:

NSURL *url = [[NSURL alloc]initWithString:@"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
© www.soinside.com 2019 - 2024. All rights reserved.