【问题标题】:iPhone base64 corrupted when posted to php scriptiPhone base64 在发布到 php 脚本时损坏
【发布时间】:2013-01-08 20:40:27
【问题描述】:

在我的应用程序中,用户裁剪那里的图片我将其编码为 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

这是我发送数据的代码:

 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];

这是我在另一个视图控制器中取回它并尝试将其转回图像的时候

 -(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];
 }

一旦我发布它,我如何防止图像被损坏..或者一旦我把它拿回来,我该如何清理它或防止发生损坏!这让我发疯了。非常感谢您提供一些代码的明确答案。谢谢

这是我在发送之前将图像转换为 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];

【问题讨论】:

  • 在 PHP 方面,做一个var_dump(substr($pic_data, 0, 512)) 并发布结果。可能会给我们更多的工作机会。
  • 您确定图片在任一方向传输时都没有损坏吗?
  • @Marc B - 这就是我的想法..我将图像发送到服务器并立即将其回显到模拟器并且它已损坏..因此它在 php 端或传输过程中被损坏。 .我在xcode中记录了它并计算了字符并在我发送它之前进行了比较,它是来的字符数
  • 因为它是base64,只需在php中解码并将其保存到某个地方的普通文件中。如果是传输故障,您会在图片中间的某个地方出现垃圾。客户端/服务器端错误可能会在图片的开头或结尾添加损坏
  • 好吧,我试一试..因为我在本地执行了编码/解码以检查它是否正常工作,并且它是..所以它必须在 php 端或在传输中..我唯一的问题是..我使用的 base64 编码类是否与 php 中内置的 base64 类兼容?我在 iPhone 上使用了很多人使用的 NSDATA+BASE64 类,其次如果我在 php 中解码它会变成什么?随机字符串?一个图像?我可以将它存储为什么?

标签: php iphone ios uiimageview base64


【解决方案1】:

为什么要调用“stringByTrimmingCharactersInSet”?在我看来,这似乎是为了删除编码图像可能需要的字符......

编辑以包含我正在使用的一些代码中的示例,该代码将几个图像正确嵌入到要提交到 php 页面的 http 表单中。

我在 NSMutableData 上使用以下类别...

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

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

然后在创建 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];

另外请注意,我没有在我的应用程序之外测试过这个,所以我可能忘记了一些东西(例如我在上面的示例中没有定义的“imagePath” - 你必须为你的图像指定一个路径) ,但它应该让您很好地了解如何将一些图像附加到要提交到 php 页面的表单上。

希望这会有所帮助!

【讨论】:

  • 好的,我会删除它..但我已经补充说,在我第一次收到错误之后..我假设在运输过程中添加了行间距或结束线..但我认为它仍然无法正常工作在我删除之后
  • 另外,在你设置“NSString *param”的那一行,“pic”是图像数据吗?如果是这样,我认为您需要先获取它的 NSData 并对其进行编码,然后再将其添加到参数字符串中。
  • pic 是图像的 base64 编码。所以一旦我在请求中发送它,它就已经是一个 base64 字符串。你觉得我需要做什么?
  • 我添加了一些我使用的代码示例,它可以帮助您构建包含文件和键值对的表单提交 - 我使用它将图像和数据发送到 php 页面。
猜你喜欢
  • 2013-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-11
  • 1970-01-01
  • 2017-06-14
  • 2012-08-28
  • 1970-01-01
相关资源
最近更新 更多