2013-01-09 109 views
2

我想从URL获取图像,但我无法做到这一点。 任何人都可以让我知道出了什么问题无法从URL获取UIImage

找到下面的代码供您参考。

NSString *ImageURL = @"http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/{B690E93E-F7C9-48AF-B72A-BFF944FA6D4A}_104_9169.JPG"; 


    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]]; 

    img.image = [UIImage imageWithData:imageData]; 

其中IMG是一个UIImageView

+0

代码看起来应该可以工作(尽管url是一个未使用的变量)。我怀疑img是零。你可以NSLog(@“%@”,img);在最后一行之前。 – danh

+0

@danh:yeh它的零,但如果我打开url我有图像!!!!! –

+1

请为羽绒投票留下意见,它可以帮助我在将来 –

回答

8

我只是创建你IMAGEURL的演示中,你只需要把代码波纹管: -

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    NSString *ImageURL = @"http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/{B690E93E-F7C9-48AF-B72A-BFF944FA6D4A}_104_9169.JPG"; 


    ImageURL =[ImageURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 

    NSLog(@"img url ==%@",ImageURL); 
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]]; 
    UIImage *MYimage = [UIImage imageWithData:data]; 

    NSLog(@"==%@",MYimage); 
    [imgview setImage:MYimage]; 

} 

下载演示中,我刚创建的图片网址: -

http://www.sendspace.com/file/m966ae

谢谢:)

+0

那里是...谢谢兄弟..它的工作现在 –

+0

我们怎么能在android中执行android –

+0

在android中可以用%7d替换{with%7b并替换} –

0

这是因为你有“{”和“}”在你IMAGEURL,所以你不能让你的形象,所以只需更换这个括号。

-(NSString*)replace:(NSString*)string 
{ 
    NSString *str = [[string stringByReplacingOccurrencesOfString:@"{" withString:@"%7B"] stringByReplacingOccurrencesOfString:@"}" withString:@"%7D"]; 

    return str; 
} 
+0

你能解释为什么replacementOccurrencesofString ...? –

+0

我也怀疑这一点,但我复制了网址到浏览器中并加载。 – danh

+0

我的网址无法正常工作,如果我将 –

0

试试这个.......

NSString *ImageURL = @"http://images.pcmac.org/SiSFiles/Schools/TN/JacksonMadisonCounty/RoseHillMiddle/Uploads/Locations/{B690E93E-F7C9-48AF-B72A-BFF944FA6D4A}_104_9169.JPG"; 
NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:ImageURL]]; 
UIImage *IMG = [UIImage imageWithData:data]; 
img.image = IMG; 
0

你必须创建以下列方式你的URL对象:

NSURL *url = [NSURL URLWithString:[ImageURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; 

然后使用该URL来获取数据。希望它能为你工作。

0

有多种方式从Url获​​取图片。你可以使用任何人。但我试过的最快的是

-(UIImage*)getImageFromURLwithUrl:(NSString*)imgURLStr 
{ 
    NSMutableURLRequest *requestWithBodyParams = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:imgURLStr]]; 
    NSData *imageData = [NSURLConnection sendSynchronousRequest:requestWithBodyParams returningResponse:nil error:nil]; 
    UIImage *image = [UIImage imageWithData:imageData]; 

    return image; 
}