This is my code:
[self.webScraper scrape:#"https://fordonsfraga.transportstyrelsen.se/fragapaannatfordon.aspx"
selector:#"//*[#id=\"frmFordonsFraga\"]/table[3]/tbody/tr[7]/td[1]/img"
handler:^(NSArray *elements, NSError *error) {
NSLog(#"Load %lu elements.", (unsigned long)elements.count);
for (NSDictionary* img in elements) {
NSString* url = [[img objectForKey:#"attributes"] objectForKey:#"src"];
NSLog(#"%#",url);
NSString* imgUrl = [NSString stringWithFormat:#"https://fordonsfraga.transportstyrelsen.se/%#", url];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
UIImage *image = [UIImage imageWithData:data];
_logga.image =image;
NSUInteger len = [data length];
NSFC
NSString * string = [[NSString alloc] initWithData:[data base64Encoding] encoding:NSUTF8StringEncoding];
NSLog(#"%#", string);
}
}];
Basically it downloads the captcha image and I wanna turn that data into a string to answer the captcha? The image displays correctly.
Any help is GREATLY appreciated!
You need to extract string from image by using OCR (optical character recognition). You can use OCR libraries (like tesseractor leptonica).check Link, you can get samples.
You should do some image processing for that and it's not that easy. Check OpenCv - it's a successful open-source library.
http://opencv.org
Related
I'm trying to insert a base 64 image into UIImage in Objective-C I do the following:
I have the user's image into a NSURL
NSURL *url = [NSURL URLWithString: [fetchDefaults objectForKey:#"img"]];
Then I cast the url, into a NSString
NSString *string=[NSString stringWithFormat:#"%#",url];
Then I clean the string, and add the prefix "data:application/octet-stream;base64," also tried with "data:image/jpg;base64,"
NSMutableString *tempStr = [NSMutableString stringWithString:string];
[tempStr replaceOccurrencesOfString:#" " withString:#"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [tempStr length])];
NSString *temp = [[NSString stringWithFormat:#"data:application/octet-stream;base64,%#",tempStr] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
And finally the string is cast to an NSData to be inserted into UImage
NSData *dat = [[NSData alloc]initWithBase64EncodedString:temp options:NSDataBase64DecodingIgnoreUnknownCharacters];
[avatar setImage:[UIImage imageWithData:dat]];
Despite of value of dat is not nil, when I set the image to the UIImage the image isn't showed, any idea of what am I doing wrong?
From what I understand you have your base64 string in fetchDefaults.
/*Get base64 string*/
NSString *base64 = [fetchDefaults objectForKey:#"img"];
Use this NSData category: https://searchcode.com/codesearch/view/40028750/
/*Convert base64 to NSData object*/
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64];
/*Convert data to UIImage object*/
UIImage *image = [[UIImage alloc] initWithData:data];
I'm converting an image that I retrieved from a URL to base 64 using this code.
NSURL* imageUrl = [NSURL URLWithString:url];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
UIImage* uiImage = [UIImage imageWithData: urlData];
NSData* imageData = UIImagePNGRepresentation(uiImage);
NSData* base64 = [imageData base64EncodedDataWithOptions:0];
return [NSString stringWithUTF8String:[base64 bytes]];
the image url: https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0
the generated base64 image.
iVBORw0KGgoAAAANSUhEUgAAANwAAADcCAMAAAAshD+zAAAABlBMVEX///8AAABVwtN+AAAAHGlET1QAAAACAAAAAAAAAG4AAAAoAAAAbgAAAG4AAASMOw2BmAAABFhJREFUeAHsmdFq5VYQBO3//+lADqgKUZcjpNU6xLNP5e7puVLPTWI2X99/6s9X/WF5uV/Y3/gSH6L3P1vF04lYKRHEnpdTF5dwLnetJr5tEEk0EfZ8LdXFJZyv5bWa9HU7kOQhGbDna6kuLuFv+Vr6+3KVVSCRFLHVp0RwF2cyyXE4Rzci6f6HJuOENrZ25mSKbP/e1Zh5RG861BQP92v3kbu4NhU6DtfkTiOtllPUJnyJILZ2Yu/IcXiXKp+0HiRFpfElgtjaib0jx+FdqnzSepAUlcaXCGJrJ/aOHId3qfJJ60FSVBpfIoitndg7chzepconrQdJUWl8iSC2dmLvyHF4lyqftB4kRaXxJYLY2om9I8fhXap80nqQFJXGlwhiayf2jhyHSaE15SSiiLzEDZLRy0lMZKfs/C+q/MTehAoRR9sRmXm51QWNuRs4fWxRTiKKCEncIJm53OqCwtwNnD62KCcRRYQkbpDMXG51QWHuBk4fW5STiCJCEjdIZi63uqAwdwOnjy3KSUQRIYkbJDOXW11QmLuB08cW5eRGxM5fitL+L14ua8inlwhmXGJixxlNH1uUkxsRey63qqQRVZuYk1ljxiX2pkPNycO991d72pnIetnzcirjX+yaDlXjh2bAt3ow9vzbcnVxVKOvYv91urpL7E2HqsyhGfCtHow9l1tdHNW8fTk+SKR7JDIqO0X5YE7qRdMnLspJxCTFEwnJTlE+mJPzchS0qGtCLTrvOP9MRk6K8sGcnMtR0KKuCbXovOP8Mxk5KcoHc3IuR0GLuibUovOO889k5KQoH8zJuRwFLeqaUIvOO84/k5GTonwwJ3/f5ahhR1T3+Jfc46Ny5+FuwXF4G4sB0vNyqwtK2nXD5HXyTvh6nknSc7n
I figured out the image is only halved because I checked using this tool.
http://codebeautify.org/base64-to-image-converter
Is there anyway I can generate a base64image String that contains the whole image?
In terms of why it's getting cut off, I suspect you're looking at the base64 string in the debugger, which will truncate it. Actually NSLog the string and you'll see it's longer than what you're seeing in the debugger.
A couple of other unrelated observations:
You should not use stringWithUTF8String with [base64 bytes] because the NSData will not be null terminated. If you really needed to convert it to a string, you'd use initWithData rather than stringWithUTF8String:
return [[NSString alloc] initWithData:base64 encoding:NSUTF8StringEncoding];
As others have pointed out, you can bypass the creation of the NSData of the base64 altogether, and create the string directly:
return [imageData base64EncodedStringWithOptions:0];
I'm not sure why you're taking the NSData from the server and round tripping it through a UIImage at all. You can theoretically just encode the data from the server directly:
NSURL* imageUrl = [NSURL URLWithString:url];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
return [urlData base64EncodedStringWithOptions:0];
The server is already returning you the NSData of a PNG representation. You don't need to do that UIImage and UIImagePNGRepresentation stuff at all. You're actually generating a PNG that is considerably larger than the one the server returned to you.
I'd advise against using dataWithContentsOfURL, because that's a synchronous network call. You probably should use NSURLSession and change this to be an asynchronous method.
NSURL* imageUrl = [NSURL URLWithString:#"https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0"];
NSData *data = [NSData dataWithContentsOfURL:imageUrl];
UIImage *image = [UIImage imageWithData:data];
NSString *base64 = [self encodeToBase64String:image];
To convert your image to base64 String use following code:
- (NSString *)encodeToBase64String:(UIImage *)image {
return [UIImagePNGRepresentation(image) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
}
That base64 will give you full image. Tested with your given image
Here is base 64 :
https://gist.github.com/anonymous/6d76e3ad852b4879ab097e6a1b3e68a2
To convert your UIImage into base64 string you can use this code.
NSString *base64String = [UIImagePNGRepresentation(uiImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
Here is the code.
NSURL* imageUrl = [NSURL URLWithString:#"https://api.qrserver.com/v1/create-qr-code/?data=somedata&size=220x220&margin=0"];
NSData* urlData = [NSData dataWithContentsOfURL:imageUrl];
UIImage* uiImage = [UIImage imageWithData: urlData];
NSString *base64String = [UIImagePNGRepresentation(uiImage) base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSLog(#"%#",base64String);
I checked the result string on http://codebeautify.org/base64-to-image-converter
Try it, Hope it helps.
This is working perfectly
UIImage *img = [UIImage imageNamed:#"QRcode.png"];
NSString *base64 = [UIImagePNGRepresentation(img)base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
NSLog(base64);
The printed base64 String can be converted back to image in the URL you provided
I'm using the below to set my imageView with a url (located in path). Yes, the URL data is returned successfully, but for some reason, my imageView remains blank (just white?)
And yes, I've hooked up my imageView property... Any idea what's wrong? Should I be using a different block of code to accomplish this?
Viewcontroller.m
NSMutableDictionary *viewParamsDogs = [NSMutableDictionary new];
[viewParamsDogs setValue:#"mydogs" forKey:#"view_name"];
[DIOSView viewGet:viewParamsDogs success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.dogData = [responseObject mutableCopy];
[operation responseString];
NSDictionary *dic = [responseObject valueForKey: #"field_pet_photo_path"];
NSArray *arr = [dic valueForKey: #"und"];
NSDictionary *dic2= [arr objectAtIndex : 0];
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSLog(#"This is path %#", path);
if([path length]>0) {
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = image;
} else {
NSString *ImageURL = #"http://url.ca/paw.png";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.dogimageView.image = [UIImage imageWithData:imageData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
Path:
[5111:1673330] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
)
NSLog(#"This is path %#, %#", path, NSStringFromClass(path.class)); returns:
2016-04-14 13:18:39.590 [5225:1700657] This is path (
"http://url.com/default/files/stored/1460659054.jpg"
), __NSCFString
I recommend usage of AFNetworking https://github.com/AFNetworking/AFNetworking for all networking connect features.
Import UIImageView+AFNetworking.h at beginning of file
#import "UIImageView+AFNetworking.h"
Get path from dic2
NSString *path = dic2[#"safe_value"];
Check if path is a string
if (![path isKindOfClass:[NSString class]]) {
return;
}
Create a NSURL object from string
NSURL *imageUrl = [NSURL URLWithString:path];
Set imageUrl to UIImageView
[self.dogimageView setImageWithURL:imageUrl];
You could check the full code in my gist https://gist.github.com/MaciejGad/fa8cb80dfc73ea55edeedb75418ea2ec
Edit:
the reason of error was the path that was set as:
NSString *path = #"(
\"http://url.com/default/files/stored/1460659054.jpg\"
)";
to change to normal URL we need to trim it:
NSMutableCharacterSet *characterSetToTrim = [NSMutableCharacterSet characterSetWithCharactersInString:#"()\""];
[characterSetToTrim formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
path = [path stringByTrimmingCharactersInSet:characterSetToTrim];
after this trimming path should be http://url.com/default/files/stored/1460659054.jpg
Try like this,
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
and You can use great library SDWebImage for caching image. When image comes from server use of this library is very helpful. Hope this will work.
Update :
NSString *path = [NSString stringWithFormat:#"%#", [dic2 valueForKey: #"safe_value"]];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
self.dogimageView.image = [[UIImageView alloc] initWithImage:image];
Try this. :)
Try using dataWithContentsOfURL:options:error: instead and look if there is any error message there
I'm trying to set my imageView with the url returned in the JSON data below in "value" (secondLink). When I use the following code, it returns the entire block in JSON through my XCode console - what should my code look like if I ONLY want the image's URL to be returned (right now, I assume it's trying to set the imageView with EVERYTHING returned in secondLink)?
ViewController.m
NSString *secondLink = [[[[DIOSSession sharedSession] user] objectForKey:#"field_photo_path"] objectForKey:#"safe_value"];
NSLog(#"This is second link %#", secondLink);
if([secondLink length]>0) {
NSString *ImageURL = secondLink;
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
} else {
NSString *ImageURL = #"defaulturl.com";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
self.imageView.image = [UIImage imageWithData:imageData];
}
JSON data
{
und = (
{
format = "<null>";
"safe_value" = "http://myurl.com/sites/default/files/stored/photo.jpg";
value = "http://myurl.com/sites/default/files/stored/photo.jpg";
}
);
}
In field_photo_path there is a dictionary und which contains an array.
The first item in the array is a dictionary containing the key safe_value.
It assumes that user is also a dictionary (at least it responds to objectForKey:)
NSDictionary *user = [[DIOSSession sharedSession] user];
NSString *secondLink = user[#"field_photo_path"][#"und"][0][#"safe_value"];
I am trying to convert binary to NSData, and I am able to get data but uiimage is still nil. Below is my code. Please can anyone help me on this.
NSData *data = [self dataFromBase64EncodedString:[dictionary objectForKey:#"object"]];
UIImage *image = [UIImage imageWithData:data];
-(NSData *)dataFromBase64EncodedString:(NSString *)string{
if (string.length > 0) {
NSString *data64URLString = [NSString stringWithFormat:#"data:;base64,%#", string];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
return data;
}
return nil;
}
Your url seems to be missing the base url.
NSString *data64URLString = [NSString stringWithFormat:#"data:;base64,%#", string];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:data64URLString]];
Based on the above.. the url is set to "data:;base64,
shouldnt it be something like "http://my.server.com/imageurl"