我是Objective-c的新手。我需要在第一个函数中选择的图像在第二个函数中上传:
- (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
}
在编辑注释之间添加的代码是我用来上传图片的代码
答案 0 :(得分:2)
您既不应使用UIImageJPEGRepresentation
也不应使用UIImagePNGRepresentation
。这些将丢失图像的元数据,使文件变大(或者如果选择JPEG压缩因子使NSData
变小,则会降低图像质量等)。
我建议您保存UIImagePickerControllerReferenceURL
,然后,当用户选择保存图片时,您将返回到照片框架并检索基础的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];
}
当您上传图片时,请从照片框架中检索原始资源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
现已弃用,您绝不应该执行同步网络请求):
- (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];
}];
}
}
顺便说一句,我以编程方式确定mime类型的例程(因为你真的不能假设图像是JPEG;它也可以是PNG,以及其他类型)如下: / p>
- (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版本时),请告诉我。
答案 1 :(得分:1)
您正在将拾取的图像指定给imageView。因此,您可以使用unionAll()
的{{1}}属性访问它。
您可以访问:
image
答案 2 :(得分:0)
我在我的演示项目中完成了您的要求。我使用UIIMagePicker委托函数
选择了图像
@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;
}
&#13;
从该方法我调用了另一个函数 - &gt; displayImage,我用它在UIImageView中显示图像。以下是代码。