我有一个图像的URL(从UIImagePickerController获取)但我不再拥有内存中的图像(该URL是从以前的应用程序运行中保存的)。我可以再次从URL重新加载UIImage吗?
我看到UIImage有一个imageWithContentsOfFile:但我有一个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:,然后是_CFStringIsLegalURLString,然后是CFStringGetLength,然后是 forwarding_prep_0 ,然后是转发< / strong>,然后 - [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";
答案 0 :(得分:312)
你可以这样做(同步但紧凑):
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:MyURL]]];
更好的方法是使用Apple的LazyTableImages来保持交互性。
答案 1 :(得分:27)
您可以尝试SDWebImage,它提供:
快速举例:
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
答案 2 :(得分: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 (不幸的是它不是轻量级的)。
答案 3 :(得分: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)
答案 4 :(得分:6)
如果你真的,绝对肯定确保NSURL是一个文件网址,即[url isFileURL]
保证在你的情况下返回true,那么你可以简单地使用:
[UIImage imageWithContentsOfFile:url.path]
答案 5 :(得分: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"];
}
});
});
答案 6 :(得分:4)
查看here以上提供的AsyncImageView
。一些很好的示例代码,甚至可以为您提供“开箱即用”。
答案 7 :(得分:4)
AFNetworking通过占位符支持将异步映像加载到UIImageView中。它还支持异步网络,以便与API一起使用。
答案 8 :(得分:3)
确保从iOS 9启用此设置:
Info.plist 中的应用传输安全设置,以确保从网址加载图片,以便下载图片并进行设置。
并编写此代码:
NSURL *url = [[NSURL alloc]initWithString:@"http://feelgrafix.com/data/images/images-1.jpg"];
NSData *data =[NSData dataWithContentsOfURL:url];
quickViewImage.image = [UIImage imageWithData:data];
答案 9 :(得分:2)
使用Swift 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()
})
}
}
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 :(得分:0)
通过网址加载图像的最佳,简便方法是通过以下代码:
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
。
它将在另一个线程中加载图像,因此不会减慢您的应用程序加载速度。
答案 11 :(得分:0)
本地 URL 非常简单,只需使用这个:
UIImage(contentsOfFile: url.path)