Get image from Webpage - objective-c

What I am trying to do is to get image from that url
www.floraphotographs.com/showrandomiphonestuff.php?color=red&session=5345
The site displays a random image everytime , I need to be able to get the image in a NSImage object and display on the screen

Grab the data like so:
NSURL * url = [NSURL URLWithString:#"http://www.flora...."];
NSData * data = [NSData dataWithContentsOfURL:url];
Then stick it in a UIImage:
UIImage * image = [UIImage imageWithData:data];
Then put it in a UIImageView:
imageView.image = image;

Related

Converting a Base64 String into a UIImage

I have looked at similar answers to this type of question but am still falling short of converting a Base64 encoded string into a UIImage correctly. I have used http://www.freeformatter.com/base64-encoder.html to test my string and can successfully get an image back as a response.
However, when I use initWithBase64EncodedString, I get a nil response. Below is the code I am using and an example of the Base64 string that I used to test with. What am I missing here?
Code:
imageData = [[NSData alloc] initWithBase64EncodedString:checkBytesString options:0];
checkImage = [UIImage imageWithData:imageData];
String (It is rather large so I am sharing it via OneDrive):
https://onedrive.live.com/redir?resid=60AA391B8FEA9C36!107&authkey=!AFK_y5UHOFsdYsKZI&ithint=file%2c.rtf
Answer was to use an external library, NSData+Base64. It implements method dataFromBase64String that returned imageData properly so it could be converted into an image.
https://github.com/l4u/NSData-Base64
imageData = [NSData dataFromBase64String:frontCheckBytesString];
checkImage = [UIImage imageWithData:imageData];
Simple in iOS 7 onwards
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData
{
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
UIImage *zeroImage = [[UIImage alloc]init];
if(![strb64Image isEqualToString:#""] && strb64Image)
{
zeroImage = [self decodeBase64ToImage:strB64Image];
}

Cache Image From URL working, but returns blank image?

I have two methods, first checks if I've already downloaded the image, and if not retrieves the image from a URL and caches it to my docs directory in my app. If it has been, it simply retrieves it, and if I have a internet connection, will re-download it. Here are the two methods:
- (UIImage *) getImageFromUserIMagesFolderInDocsWithName:(NSString *)nameOfFile
{
UIImage *image = [UIImage imageNamed:nameOfFile];
if (!image) // image doesn't exist in bundle...
{
// Get Image
NSString *cleanNameOfFile = [[[nameOfFile stringByReplacingOccurrencesOfString:#"." withString:#""]
stringByReplacingOccurrencesOfString:#":" withString:#""]
stringByReplacingOccurrencesOfString:#"/" withString:#""];
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#.png", cleanNameOfFile]];
image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
if (!image)
{
// image isn't cached
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
[self saveImageToUserImagesFolderInDocsWithName:cleanNameOfFile andImage:image];
}
else
{
// if we have a internet connection, update the cached image
/*if (isConnectedToInternet) {
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
[self saveImageToUserImagesFolderInDocsWithName:cleanNameOfFile andImage:image];
}*/
// otherwise just return it
}
}
return image;
}
Here's to save the image
- (void) saveImageToUserImagesFolderInDocsWithName:(NSString *)nameOfFile andImage:(UIImage *)image
{
NSString *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"Documents/%#.png", nameOfFile]];
[UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];
NSLog(#"directory: %#", [[UIImage alloc] initWithContentsOfFile:pngPath]);
}
The image has already been successfully downloaded and cached to my documents directory (I know because I can see it in the File system). And it successfully re loads the image the first time I call this method, but once I go to another view, and re-call this method when I come back to the same view, it's blank. Yet, the URL is correct. What's wrong here?
1) You should not be writing into a hardcoded path as you do (ie "Documents/xxx"), but rather ask for the Application Support directory, use it, and also mark files so that they don't get uploaded to iCloud (unless you want that). See this link on the specifics. Create a subfolder in it and mark it as not for iCloud backup.
2) Try changing:
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:nameOfFile]]];
to
image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]]];
Maybe, you should do:
image = [UIImage imageWithContentsOfFile: nameOfFile];

How to compose an image from GUI elements on iOS?

I need to form an image by composing some visual elements and save it on disk. The question is: how to "screenshot" a certain area of a view? Possibly a view that is not visible, so the procedure can be executed unnoticed?
This code snippet shows how to render a view to a UIImage:
UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
And this snippet shows how to save a UIImage as a JPEG or a PNG:
NSString *pngPath = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents/Test.png"];
NSString *jpgPath = [NSHomeDirectory()
stringByAppendingPathComponent:#"Documents/Test.jpg"];
[UIImageJPEGRepresentation(viewImage, 1.0) writeToFile:jpgPath atomically:YES];
[UIImagePNGRepresentation(viewImage) writeToFile:pngPath atomically:YES];

Create a UIImage with a URL in iOS

To create an UiImage with a image file, I use the code as below:
UIImage *aImage = [[UIImage imageNamed:#"demo.jpg"]autorelease];
If I want to create an UiImage with the URL http://example.com/demo.jpg, how to do that?
Thanks
UPDATE
This is a three step process. First you will create an NSURL object to hold the URL we are attempting to access. We will supply this URL to the NSData class method, +dataWithContentsOfURL: to obtain the image over the network as raw data, then use the +imageWithData: class method on UIImage to convert the data into an image.
NSURL *imageURL = [NSURL URLWithString:#"http://example.com/demo.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
Please note that +dataWithContentsOfURL: executes a synchronous network request. If you run this on the main thread, it will block the UI until the image data is received from the network. Best practice is to run any network code on a background thread. If you're targeting OS 4.0+ you could do something like this...
NSURL *imageURL = [NSURL URLWithString:#"http://example.com/demo.jpg"];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
dispatch_async(dispatch_get_main_queue(), ^{
// Update the UI
self.imageView.image = [UIImage imageWithData:imageData];
});
});
Here's what the same code might look like in Swift:
let image_url = NSURL("http://i.imgur.com/3yY2qdu.jpg")
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
let image_data = NSData(contentsOfURL: image_url!)
dispatch_async(dispatch_get_main_queue()) {
// update some UI
let image = UIImage(data: image_data!)
self.imageView.image = image
}
}
For anyone looking to load image from the web the following library may be helpful:
https://github.com/rs/SDWebImage
It's a UIImageView category which handles async loading and image caching from url.

Thumbnail from NSURL

I am loading files that are downloaded from the web in a UIWebView (HTML files).
Is there a way to create a UIImage from an HTML file located in the Documents folder?
The goal is to auto generate thumbnails without needing to manual create them...
Update
My train of thought would be to do something in the line of:
NSString * s = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"html"];
UIImage *image = [[UIImage alloc] initWithData:
[NSData dataWithContentsOfURL:url]];
Which of course does not work in this case!
Thanks!
S.
I found this solution here
UIGraphicsBeginImageContext(yourWebView.bounds.size);
[yourWebView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultImageView = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
resultImageView will be an image that contains the render of yourWebView.
If you want to shrink it down to a thumbnail size from there, I like Trevor's UIImage category for that purpose.