简体   繁体   English

iPhone base64在发布到php脚本时损坏

[英]iPhone base64 corrupted when posted to php script

In my app the user crops there picture i encode it to a base64 string and send it to my php script.I am using the NSData+base64 class However, when the app goes to retrieve the string again to convert back into a picture I get this error: 在我的应用程序中,用户在其中裁剪图片,然后将其编码为base64字符串,然后将其发送至php脚本。我使用的是NSData + base64类,但是,当应用程序再次检索字符串以转换回图片时,我得到了这个错误:

Jan  8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Corrupt JPEG data:214        extraneous bytes before marker 0x68  Jan  8 14:21:33 Vessel.local Topic[11039] <Error>: ImageIO: JPEG Unsupported marker type 0x68

Here is the code in which i send off the data: 这是我发送数据的代码:

 NSString *urlString = [NSString stringWithFormat:@"http://myurl.php"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url                cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
[request setHTTPMethod:@"POST"];
NSString *param = [NSString stringWithFormat:@"username=%@&password=%@&email=%@&quote=%@&pic=%@",user,password,email,quote,pic];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request  delegate:self startImmediately:YES];

Here is when i get it back in another view controller and attempt to turn it back into a image 这是当我在另一个视图控制器中将其取回并尝试将其重新转换为图像时

 -(void)connectionDidFinishLoading:(NSURLConnection *)connection{

homeData = [NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];

NSString *decodeString = [[homeData objectAtIndex:0]objectForKey:@"profile_pic" ];
decodeString = [decodeString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
int returnNUM = [decodeString length];
NSLog(@"RETURN STRING=%d",returnNUM);
NSData *data = [[NSData alloc] initWithData:[NSData dataFromBase64String:decodeString]];

profilepic = [[UIImageView alloc]initWithFrame:CGRectMake(5, 4, 120, 120)];
profilepic.image = [UIImage imageWithData:data];
UIGraphicsBeginImageContextWithOptions(profilepic.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:profilepic.bounds cornerRadius:80.0] addClip];
[pic drawInRect:profilepic.bounds];
profilepic.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:profilepic];
 }

How can i prevent the image from being corrupted once i post it..or once i get it back how can i clean it or prevent the corruption thats happening! 一旦我将其发布..或一旦我将其取回,如何防止图像损坏?如何清洁或防止发生损坏! This is driving me nuts..a clear answer with some code would be highly appreciated.Thanks 这真让我发疯..非常感谢您提供一些代码的明确答案。

This is the code that I use to convert the image into base64 before i send it. 这是在发送图像之前用于将图像转换为base64的代码。

    NSData *imageData = UIImageJPEGRepresentation(crop, 1.0);
    NSString *baseString = [imageData base64EncodedString];
    int original =[baseString length];
    NSLog(@"orignal String=%d",original);
    [self register:username.text withPass:password.text withEmail:email.text withQuote:quote.text withPic:baseString];

Why are you doing the "stringByTrimmingCharactersInSet" call? 为什么要进行“ stringByTrimmingCharactersInSet”调用? That would seem to me to remove characters that the encoded image probably needs... 在我看来,这似乎删除了编码图像可能需要的字符...

Edit to include example from some code I'm using which correctly embeds a couple images into a http form to be submitted to a php page. 编辑以包括我正在使用的一些代码中的示例,该代码正确地将几个图像嵌入到http表单中以提交到php页面。

I use the following Category on NSMutableData... 我在NSMutableData上使用以下类别...

The following goes inside NSMutableData+HTTP.h NSMutableData + HTTP.h内部包含以下内容

@interface NSMutableData (HTTP)

-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary;
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary;

@end

The following goes inside NSMutableData+HTTP.m NSMutableData + HTTP.m内部包含以下内容

#import "NSMutableData+HTTP.h"

@implementation NSMutableData (HTTP)

//use for attaching a file to the http data to be posted
-(void)appendFileAtPath:(NSString*)fullFilePath withFormKey:(NSString*)formKey withSuggestedFileName:(NSString*)suggestedFileName boundary:(NSData*)boundary{

    [self appendData:boundary]; 

    [self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", formKey, suggestedFileName] dataUsingEncoding:NSUTF8StringEncoding]];

    [self appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [self appendData:[NSData dataWithContentsOfFile:fullFilePath]];

    [self appendData:[@"Content-Encoding: gzip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [self appendData:boundary]; 
}

//use for attaching a key value pair to the http data to be posted
-(void)appendKey:(NSString*)key value:(NSString*)value boundary:(NSData*)boundary{    
    [self appendData:boundary]; 
    [self appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
    [self appendData:boundary]; 
}

@end

Then in my code that creates an http form submission I do the following to attach a couple images and key-value pairs (via the category methods above) to the form... (Note: I have not included the NSURLConnectionDelegate methods that you'll need to implement if you want to track the progress of the form submission.) 然后,在创建http表单提交的代码中,我执行以下操作以将几个图像和键值对(通过上面的类别方法)附加到表单...(注意:我没有包括您要使用的NSURLConnectionDelegate方法如果您想跟踪表单提交的进度,则需要实施。)

NSString *boundaryString = @"0xKhTmLbOuNdArY";
NSData *boundaryData = [[NSString stringWithFormat:@"\r\n--%@\r\n", boundaryString] dataUsingEncoding:NSUTF8StringEncoding];
NSString *phpReceiverURL = @"http://www.someurl.com/somephppage.php";

NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setTimeoutInterval:30];
[theRequest setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[theRequest setHTTPShouldHandleCookies:NO];
[theRequest setURL:[NSURL URLWithString:phpReceiverURL]];
[theRequest setHTTPMethod:@"POST"]; 

[theRequest addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundaryString] forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];

//add some image files to the form
[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"cat.jpg"] 
    withFormKey:@"cat"  
    withSuggestedFileName:@"received-cat.jpg"
    boundary:boundaryData
];

[body appendFileAtPath:[imagePath stringByAppendingPathComponent:@"dog.jpg"] 
    withFormKey:@"dog"  
    withSuggestedFileName:@"received-dog.jpg"
    boundary:boundaryData
];

//add some key value pairs to the form
[body appendKey:@"testkeyone" value:@"testvalueone" boundary:boundaryData]; 
[body appendKey:@"testkeytwo" value:@"testvaluetwo" boundary:boundaryData]; 

// setting the body of the post to the reqeust
[theRequest setHTTPBody:body];

//create the connection
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

Also note I haven't tested this outside of my app so I may have forgotten something (such as "imagePath" which I haven't defined in the example above - you'll have to specify a path for your images), but it should give you a good idea of how to attach some images to a form to be submitted to a php page. 还要注意,我还没有在应用程序外部进行过测试,因此我可能忘记了一些东西(例如我在上例中未定义的“ imagePath”-您必须为图像指定路径),但是应该给你一个很好的想法,如何将一些图像附加到要提交到php页面的表单上。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM