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];
}
Related
I tried the solution given here using:
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
The encoded string I am getting is different from the one I can get via uploading an image on web tool like.
Simply my string is different from web and is not able to decode on the web for an image.
my other implementation is
-(NSString*)base64StringForImage{
UIImage *originalImage =_image_PreviewImage.image;
UIGraphicsBeginImageContext(originalImage.size);
[originalImage drawInRect:CGRectMake(0, 0, 1000, 1000)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imgData=UIImagePNGRepresentation(newImage);
NSString *base64String = [imgData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
return base64String;
}
originalImage and newImage both have the images. testing out reducing the image sizes
the option with
NSDataBase64EncodingEndLineWithLineFeed
given encoded string with half image like the below
How can I write the code below in Objective C:
let strPictureURL: String = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String)!
self.ivUserProfileImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: strPictureURL)!)!)
I have been trying to rewrite the code in objective C and don't find a way to set an image from a NSString. So far I have managed this:
NSString *strPictureURL = [[[result objectForKey:#"picture"] objectForKey: #"data"] objectForKey:#"url"];
NSString *strPictureURL = [[[result objectForKey:#"picture"] objectForKey: #"data"] objectForKey:#"url"];
self.ivUserProfileImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strPictureUrl]]];
I managed to make it work like this:
NSString *strPictureURL = [[[result objectForKey:#"picture"] objectForKey: #"data"] objectForKey:#"url"];
UIImage *im = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString:strPictureURL]]];
[self.imageProfilePic setImage:im];
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];
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;
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.