How to convert image into binary format in iOS? - ios

I am working on a project where I need to upload image to my server. I want to store my image's binary data to BLOB data type field in database. Therefore I need to convert my image into binary format. So that it can be saved on servers database.
So How to convert an image into binary format? Please advise.

You can use the CoreGraphics' method UIImagePNGRepresentation(UIImage *image), which returns NSData and save it.
and if you want to convert it into again UIImage create it using [UIimage imageWithData:(NSData *data)] method.
Demo to send your UIImage to Server
- (void)sendImageToServer {
UIImage *yourImage= [UIImage imageNamed:#"image.png"];
NSData *imageData = UIImagePNGRepresentation(yourImage);
NSString *postLength = [NSString stringWithFormat:#"%d", [imageData length]];
// Init the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:#"http://yoururl.domain"]]];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:imageData];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection) {
}
[request release];
}

Use:
NSData *data = UIImageJPEGRepresentation(image, 1.0);
//OR
NSData *data = UIImagePNGRepresentation(image);
According to requirement.

Related

How to use GData framework in iOS app to upload images to Picasa?

In my app, I have an imageView, I want to post the image to Picasa.
I got some suggestion to use GData Framwork. I downloaded it from
code.google.com/p/gdata-objectivec-client/downloads/list
But, when I add the .a file in my Build phases, it is displayed as red. I have tried all the method in SO, as well as other forums.
Is there any other way to upload image to Picasa.
Any help would be appreciated.
I don't have an app to test this with, but I've translated the php-curl solution from this SO question.
NSString *authCode = [NSString stringWithFormat:#"GoogleLogin auth=",#"ACCESS CODE FROM OAUTH2"];
NSString *userId = #"USER ID GOES HERE";
NSString *albumId = #"ALBUM ID GOES HERE";
NSString *albumUrl = [NSString stringWithFormat:#"https://picasaweb.google.com/data/feed/api/user/%#/albumid/%#",userId, albumId];
// To get the data from a PNG file
NSData *postData = UIImagePNGRepresentation([UIImage imageNamed:#"YOUR IMAGE"]);
// To get the data from a JPEG file
//NSData *postData = UIImageJPEGRepresentation([UIImage imageNamed:#"YOUR IMAGE"], 0.9f);
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
// Init and set fields of the URLRequest
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"POST"];
[request setURL:[NSURL URLWithString:[NSString stringWithString:albumUrl]]];
[request setValue:#"image/jpeg" forHTTPHeaderField:#"Content-Type"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"2" forHTTPHeaderField:#"GData-Version"];
[request setValue:authCode forHTTPHeaderField:#"Authorization"];
[request setHTTPBody:postData];
NSURLResponse* rep = nil;
NSError *err = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&rep error:&err];
if (data && !err) {
//Do something with the response
}
Hope this helps.

How to upload String and Image using ASIFormDataRequest?

I want to upload follow Log Strings along with UIImage,
HOw can I achieve such objective????
I can see to send only image , but i want to send image along with text data using this ASIFormDataRequest, using POST request type.
NSLog(#"data is here %#\n%#\n%#\n%#\n%#\n",deviceID, postID, name, message, picture);
UIImage *image= [UIImage imageNamed:#"profile_avatar.png"];
NSString *strURL = #"https://abc.abc.com/comments/create";
// ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]]; // Upload a file on disk
// NSString *filename1=[NSString stringWithFormat:#"friendship.jpg"];
UIImage *image1=image;
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0);
[request setData:imageData1 withFileName:#"filename" andContentType:#"image/png" forKey:#"avatar"];
[request setRequestMethod:#"POST"];
[request addRequestHeader:#"Authorization" value:[NSString stringWithFormat:#"Basic %#",[ASIHTTPRequest base64forData:[[NSString stringWithFormat:#"username123:pass123"] dataUsingEncoding:NSUTF8StringEncoding]]]];
[request setValidatesSecureCertificate:NO];
//[request appendPostData:body];
[request setDelegate:self];
[request setTimeOutSeconds:3.0];
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
Thanks
There is one method available to send parameter as well
[request setPostValue:#"YourValue" forKey:#"YourKey"];

Seems like by uiimage encoding is altered before POST request

I'm currently working on sending uiimages to my server to be stored on the server. So I get an image from the user gallery and then encode it using Base64 and then send it to my server. However all the images I sent to my server don't show. I'm wondering whether the post request I make with the base64encodedstring alters the encoded string.
Here is what I have done.
//Upload picture to server
NSData *imageData=UIImageJPEGRepresentation(showPic.image, 1.0f);
NSLog(#"The size of the image is %i",[imageData length]);
[Base64 initialize];
NSString *strEncoded = [Base64 encode:imageData];
//NSLog(#"This is the encoded string to be uploaded %#",encodedPic);
prefs=[NSUserDefaults standardUserDefaults];
userid=[prefs stringForKey:#"userid"];
NSLog(#" %# is the userid to be used to upload the pic",userid);
NSString *poster = #"username=";
poster = [poster stringByAppendingString:userid];
poster = [poster stringByAppendingString:#"&image="];
poster = [poster stringByAppendingString:strEncoded];
NSString *post = poster;
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.example.com/server/upload"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

loading image fro MYSQL into Imageview

I have tried to find this answer for days now and cant find anything. I store url to image in my database and Im trying to get this url and load the image to a ImageView.
Users uploads a image and my PHP script makes a url to the image in the database. This is my database table: ID -> Username -> Password -> urlImage. And I have another PHP script that takes the username and askes for the urlImage.
In Xcode i want to add this: `
NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];
NSString *user = [settings valueForKey:#"username"];
NSString *post = [NSString stringWithFormat:#"username=%#&image=dummy",user];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://url.com/Wish_Profile_Pic.php"]];
NSString *postLen = [[NSString alloc] initWithFormat:#"%d" ,[post length ]];
[request setValue:postLen forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
//this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
`
This will send a request to the database sever and the server will output the urlImage. How can I view the image in the ImageView? Cant find anything about this.
NSString *post = [NSString stringWithFormat:#"username=%#&image=dummy",use];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://url.com/Wish_Profile_Pic.php"]];
NSString *postLen = [[NSString alloc] initWithFormat:#"%d" ,[post length ]];
[request setValue:postLen forHTTPHeaderField:#"Content-Length"];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) {
if(data.length) {
UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];
//try base64
if(!img) {
//NEEDS http://projectswithlove.com/projects/NSData_Base64.zip
id b64 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
id data2 = [NSData dataFromBase64String:b64];
img = [[[UIImage alloc] initWithData:data2] autorelease];
}
if(img)
self.imageView.image = img;
}
else if(e)
NSLog(#"%#", e);
}];

Sending images as part of form data from an iPhone

I've managed to get simple text data sent to a server using this code:
NSMutableString *parameterString = [[NSMutableString alloc] initWithString: #""];
[parameterString appendString:#"name=steve&"];
[parameterString appendString:#"surname=jobs&"];
[parameterString appendString:#"age=55"];
NSURL *url = [NSURL URLWithString:#"http://example.come/script/"];
request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
NSData *parameterData = [parameterString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:parameterData];
With that I can send text form data. But how can I send PNG images as well?
You could just convert the image to an NSData object, then base64 encode it to send it as a parameter.
Base64 encoding examples found here: How do I do base64 encoding on iphone-sdk?
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addData:imageData withFileName:#"image.png" andContentType:#"image/png" forKey:#"yourParamKey"];

Resources