代码之家  ›  专栏  ›  技术社区  ›  progrmr

我可以从URL加载uiimage吗?

  •  124
  • progrmr  · 技术社区  · 14 年前

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

    我看到uiimage有一个imagewithcontentsofile:但是我有一个url。我可以使用nsdata的datawithContentsOfURL:来读取URL吗?

    小精灵


    基于@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:,然后是cfStringIsleGallString,然后是cfStringGetLength,然后 转发准备 然后 转发 ,然后-[nsObject不识别选择器]。

    你知道为什么我的nsstring(photourl的地址是0x536fbe0)不响应长度吗?为什么它说它不响应-[nsurl length]?它不知道param是nsstring,而不是nsurl吗?

    编辑2


    好的,代码的唯一问题是字符串到URL的转换。如果我对字符串进行硬编码,其他一切都可以正常工作。所以我的nsstring出了点问题,如果我搞不清楚的话,我想这应该是另一个问题了。插入此行后(我从上面的控制台日志中粘贴了路径),它可以正常工作:

    photoURL = @"file://localhost/Users/gary/Library/Application%20Support/iPhone%20Simulator/3.2/Media/DCIM/100APPLE/IMG_0004.JPG";
    
    11 回复  |  直到 5 年前
        1
  •  311
  •   Krishnabhadra    12 年前

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

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

    更好的方法是使用苹果的LazytableImages来保持互动性。

        2
  •  27
  •   Muhammad Hassan Nasr    12 年前

    你可以试试 SDWebImage ,它提供:

    1. 异步加载
    2. 缓存供脱机使用
    3. 加载时出现的占位符图像
    4. 适用于UITableView

    快速示例:

        [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
        3
  •  7
  •   Fattie    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
            }
        }];
    

    正如我上面提到的,另一个伟大的图书馆现在考虑的是 哈内克 (不幸的是,它没有那么轻)。

        4
  •  6
  •   user3763002    10 年前

    以及Swift版本:

       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)
    
        5
  •  6
  •   Dhiraj Gupta    8 年前

    如果你是 真正地 ,当然可以。 积极地 确保nsurl是一个文件URL,即 [url isFileURL] 在您的情况下保证返回true,然后您可以简单地使用:

    [UIImage imageWithContentsOfFile:url.path]
    
        6
  •  5
  •   Jouhar    9 年前

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

    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"];
                }
            });
        });
    
        7
  •  4
  •   marcc    14 年前

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

        8
  •  4
  •   pauliephonic    11 年前

    AFNetworking 提供异步图像加载到带有占位符支持的uiImageView中。一般来说,它还支持异步网络来使用API。

        9
  •  2
  •   fpg1503    9 年前

    使用雨燕的方法 Extension UIImageView (源代码 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()
                })
            }
        }
    

    自定义初始值设定项和setter

        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()
        }
    }
    
        10
  •  2
  •   Nagarjun GOrozco58    8 年前

    确保从iOS 9启用此设置:

    应用传输安全设置 在里面 信息列表 确保从URL加载图像,以便允许下载图像并对其进行设置。

    enter image description here

    写下这段代码:

    NSURL *url = [[NSURL alloc]initWithString:@"https://www.google.co.in/"];
    NSData *data =[NSData dataWithContentsOfURL:url];
    quickViewImage.image = [UIImage imageWithData:data];
    
        11
  •  0
  •   jalmatari    5 年前

    通过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 .

    它将在另一个线程中加载图像,因此不会降低应用程序的加载速度。