在objective-c中上传选中的图像

我是新的objective-c。 我需要在第一个函数中select的图像上传到第二个:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; self.imageView.image = chosenImage; [picker dismissViewControllerAnimated:YES completion:NULL]; } - (IBAction)uploadPic:(UIButton *)sender { // COnvert Image to NSData NSData *dataImage = UIImageJPEGRepresentation([UIImage imageNamed:@"yourImage"], 1.0f); //added after editing // set your URL Where to Upload Image NSString *urlString = @"http://url"; // set your Image Name NSString *filename = @"uploaded_file"; // Create 'POST' MutableRequest with Data and Other Image Attachment. NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *postbody = [NSMutableData data]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[NSData dataWithData:dataImage]]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPBody:postbody]; // Get Response of Your Request NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; NSLog(@"Response %@",responseString); //end editing } 

在编辑注释之后添加的代码就是我用来上传图片的代码

您正在将选取的图像分配给您的imageView。 所以你可以使用该UIImageViewimage属性来访问它。

你可以访问像:

 - (IBAction)uploadPic:(UIButton *)sender { NSData *dataImage = UIImageJPEGRepresentation(self.imageView.image, 1.0f); // Do your stuff here } 

我已经在我的演示项目中完成了你的要求。 我已经使用UIIMagePicker委托functionselect图像

 @interface ViewController () { UIImage *chooseImage; } - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSDate *time = [NSDate date]; NSDateFormatter* df = [NSDateFormatter new]; [df setDateFormat:@"ddMMyyyy-hhmmss"]; NSString *timeString = [df stringFromDate:time]; NSString *fileName = [NSString stringWithFormat:@"%@", timeString]; chooseImage = info[UIImagePickerControllerEditedImage]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); documentsDirectoryPath = [paths objectAtIndex:0]; NSLog(@"View Controller Path:%@",documentsDirectoryPath); savedImagePath = [documentsDirectoryPath stringByAppendingPathComponent:[NSString stringWithFormat: @"%@-%d.png", fileName, num]]; num += 1; NSData *imageData = UIImagePNGRepresentation(chooseImage); [imageData writeToFile:savedImagePath atomically:NO]; [picker dismissViewControllerAnimated:YES completion:NULL]; [self displayImage]; } -(void)displayImage { self.imageView.image = chooseImage; } 

您应该既不使用UIImageJPEGRepresentation也不使用UIImagePNGRepresentation 。 那些将丢失图像的元数据,使文件变大(或者如果您selectJPEG压缩因子使NSData变小,则会降低图像)等等。

我build议你保存UIImagePickerControllerReferenceURL ,然后当用户select保存图像时,返回到Photos框架并检索图像的基础NSData

所以,确保导入Photos框架:

 @import Photos; 

另外,定义一个属性来捕获URL:

 @property (nonatomic, strong) NSURL *imageReferenceURL; 

然后在获取图像时捕获此URL:

 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { UIImage *chosenImage = info[UIImagePickerControllerEditedImage]; self.imageView.image = chosenImage; self.imageReferenceURL = info[UIImagePickerControllerReferenceURL]; [picker dismissViewControllerAnimated:YES completion:nil]; } 

当您上传图片时,从Photos框架中检索原始资产的NSData

 - (IBAction)uploadPic:(UIButton *)sender { PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[self.imageReferenceURL] options:nil]; PHAsset *asset = [result firstObject]; if (asset) { PHImageManager *manager = [PHImageManager defaultManager]; [manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { // insert your code for uploading here, referencing the `imageData` here rather than `dataImage`. // Or, I might recommend AFNetworking: // // For example, if your web service was expecting a `multipart/form-data` POST and was // going to return a JSON response, you could do something like: NSString *urlString = @"http://192.168.0.10/udazz/2.0/2.2/ios/1.0/actions.php?targ=user&subTarg=post&txtComment=123456&txtType=ff"; NSDictionary *parameters = @{@"targ" : @"user", @"subTarg" : @"post", @"txtComment" : @"123456", @"txtType" : @"ff"}; NSURL *fileURL = info[@"PHImageFileURLKey"]; NSString *filename = [fileURL lastPathComponent]; NSString *mimeType = [self mimeTypeForPath:filename]; AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; // manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // if response is string rather than JSON, uncomment this line [manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { [formData appendPartWithFileData:imageData name:@"userfile" fileName:filename mimeType:mimeType]; } success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"responseObject = %@", responseObject); } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"error = %@", error); }]; }]; } } 

或者,如果您想使用您自己的上传代码,只需将其调整为使用NSURLSession (因为NSURLConnection现在已被弃用,您不应该同步networking请求):

 - (IBAction)uploadPic:(UIButton *)sender { PHFetchResult *result = [PHAsset fetchAssetsWithALAssetURLs:@[self.imageReferenceURL] options:nil]; PHAsset *asset = [result firstObject]; if (asset) { PHImageManager *manager = [PHImageManager defaultManager]; [manager requestImageDataForAsset:asset options:nil resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) { // upload the `imageData` NSURL *fileURL = info[@"PHImageFileURLKey"]; NSString *filename = [fileURL lastPathComponent]; NSString *mimeType = [self mimeTypeForPath:filename]; NSString *urlString = @"http://192.168.0.10/udazz/2.0/2.2/ios/1.0/actions.php?targ=user&subTarg=post&txtComment=123456&txtType=ff"; NSMutableURLRequest* request= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; NSString *boundary = @"---------------------------14737809831466499882746641449"; NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; NSMutableData *postbody = [NSMutableData data]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; [postbody appendData:imageData]; [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; NSURLSessionTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:postbody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"Response %@",responseString); }]; [task resume]; }]; } } 

顺便说一句,我的程序确定MIMEtypes(因为你真的不能只是假设图像是一个JPEG;它可能是一个PNG,其他types也如此)例程如下:

 - (NSString *)mimeTypeForPath:(NSString *)path { // get a mime type for an extension using MobileCoreServices.framework CFStringRef extension = (__bridge CFStringRef)[path pathExtension]; CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, extension, NULL); assert(UTI != NULL); NSString *mimetype = CFBridgingRelease(UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType)); assert(mimetype != NULL); CFRelease(UTI); return mimetype; } 

如果您需要支持早于Photos框架的iOS版本,请使用ALAssetsLibrary获取NSData 。 如果你需要如何做的例子(只有当你需要支持8.0之前的iOS版本),让我知道。