Digital Media Mac Blogs > Mac

Creating an UIImage from a URL


A question came up over the weekend as to download an image off the internet and add it to a UIImage object on the iPhone. The answer is to create an NSData object that grabs the contents of the URL and then initialize the image with that data, as such:

id path = @"http://merrimusings.mu.nu/archives/images/groundhog2.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO];

Categories





AddThis Social Bookmark Button
Comments (10)
Read More Entries by Erica Sadun.

10 Comments

liujuncong said:

very good!

ptanzill said:

Erica,

Thanks so much for posting this code snippet - I know I have used it i several apps... However, you should know that the initWithData:cache: method has been flagged as a private API call by Apple and is grounds for rejection. The necessary change is to remove the cahe parameter... it still works great - for convenience sake, here is the code:

id path = @"http://merrimusings.mu.nu/archives/images/groundhog2.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];

To fix the "no '-initWithDatacache' method found" error, remove the "cache:NO"

AK said:

thanks for the example. Just what I was looking for.

Debss said:

I want to Create an Image View in Interface Builder,then want to add an image from URL,
Kindly give me the solution?

deb said:

I want to get an image from url onto iphone view.i write the following code;

id path = @"http://merrimusings.mu.nu/archives/images/groundhog2.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO];

but it gives warning: "no '-initWithDatacache' method found" and "unused variable 'img' ".Then i add the following'
[imgView setImage:img];
[data release];
[img release];
but again it gives warning:"no '-initWithDatacache' method found" and "UIImage mau not respond to '-setImage'"
so,please kindly give me the solution

Jimmy Bergetun said:

Thanks Erica

Is it possible to save the current image that is showing in a uiwebview instead of getting it again.

The picture that I am showing in uiwebview is constantly changing so I want to save the one that is currently being displayed.

Matt said:

Thanks - that is exactly the example I was looking for!

Federico said:

Eres feĆ­simaaaa
JAJAJAJA

tompa said:

How do you make the inverse, i.e. save an image to a jpg- or png-file given an UIImage or CGImage (using the hacked/open SDK that is)??

Leave a comment


Recommended for You

Topics of Interest

Archives


 
 


Or, visit our complete archive.