如何通过填写NSDictionary以JSON格式发送UIImage

时间:2022-03-22 21:22:59

I'm trying to send data to a server with JSON. I am able to create my NSDictionary with my objects and key parameters. But I want to send my picture, and the picture is UIImage.

我尝试用JSON发送数据给服务器。我可以用我的对象和关键参数创建我的NSDictionary。但是我想发送我的图片,图片是UIImage。

 NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"John",
                          @"First_Name",
                          @"McCintosh",
                          @"Last_name",
                          <HERE I WANT PICTURE>,
                          @"Profile_picture",
                          nil];

 // Here I convert to NSDATA 
 NSData * jsonData = [NSJSONSerialization dataWithJSONObject:mainJSON options:NSJSONWritingPrettyPrinted error:&error];

 // Sending operation :
 dispatch_async(kBgQueue, ^
                   {
                       NSData * data = [NSData dataWithContentsOfURL:@"addresSERVER"];
                       [self performSelectorOnMainThread:@selector(receivedResponseFromServer:)
                                              withObject:data
                                           waitUntilDone:YES];
                   }
                   );

So I'm wondering how can I add my picture in my NSDictionary? Because I want to send the content of my picture. If I add my object UIImage... I'll send the whole object right?

我想知道如何在NSDictionary中添加图片?因为我想发送我的图片内容。如果我添加对象UIImage。我会发送整个对象,对吧?

Thanks

谢谢

4 个解决方案

#1


7  

You should convert the UIImage to NSString. Use the category of NSData called NSDataAdditions.You can find here: NSDataAdditions category

你应该把UIImage转换成NSString。使用NSData的类别nsdataadd。您可以在这里找到:nsdataadd类别

How to Use:

如何使用:

//Convert an Image to String
UIImage *anImage;
NSString imageString = [UIImagePNGRepresentation(anImage) base64Encoding];

//To retrieve
NSData *data = [NSData dataWithBase64EncodedString:imageString];
UIImage *recoverImage = [[UIImage imageWithData:data];

#2


4  

I wouldn't typically post an image using JSON. Although it is technically possible to encode an image into text, I don't think that's how JSON is intended to be used and I would personally avoid the practice.

我通常不会使用JSON发布图像。虽然从技术上讲,将图像编码为文本是可能的,但我认为JSON并不是用来使用的,我个人会避免这种做法。

Deal with images as NSData. That's what they are. There are tons of examples online that illustrate how to do this.

将图像作为NSData处理。这是它们是什么。网上有很多例子可以说明如何做到这一点。

One common approach is to upload an image to a web server, then take the URL of the uploaded image and add that to your JSON dictionary, such that your submitted JSON dictionary carries a string representing the URL of the image to download -- not the image itself.

一种常见的方法是将图像上载到web服务器,然后获取上传图像的URL并将其添加到JSON字典中,以便提交的JSON字典携带表示要下载图像的URL的字符串——而不是图像本身。

#3


2  

You can try send UIImage with NSString like this: Swift 3:

你可以尝试用NSString发送UIImage如下:Swift 3:

if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
    var encodedString = jpegData.base64EncodedString()
    var mainJSON = [
        "First_Name" : "John",
        "Last_name" : "McCintosh",
        "Profile_picture" : encodedString
    ]

}

Objective-c:

objective - c:

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64Encoding];


 NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"John",
                          @"First_Name",
                          @"McCintosh",
                          @"Last_name",
                          encodedString,
                          @"Profile_picture",
                          nil];

This is Base64 format so you can decode this in any language

这是Base64格式,所以你可以用任何语言解码它

#4


0  

Okay, Thansk to @tolgamorf and @isaac, I tried using AFNetwork. I could do what I want. It's powerful and simple.

好的,谢谢@tolgamorf和@isaac,我试过使用AFNetwork。我可以做我想做的。这是强大的和简单的。

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"  path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg"  mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

I took the code from official documentation from here .

我从这里拿到了官方文件的代码。

Enjoy

享受

#1


7  

You should convert the UIImage to NSString. Use the category of NSData called NSDataAdditions.You can find here: NSDataAdditions category

你应该把UIImage转换成NSString。使用NSData的类别nsdataadd。您可以在这里找到:nsdataadd类别

How to Use:

如何使用:

//Convert an Image to String
UIImage *anImage;
NSString imageString = [UIImagePNGRepresentation(anImage) base64Encoding];

//To retrieve
NSData *data = [NSData dataWithBase64EncodedString:imageString];
UIImage *recoverImage = [[UIImage imageWithData:data];

#2


4  

I wouldn't typically post an image using JSON. Although it is technically possible to encode an image into text, I don't think that's how JSON is intended to be used and I would personally avoid the practice.

我通常不会使用JSON发布图像。虽然从技术上讲,将图像编码为文本是可能的,但我认为JSON并不是用来使用的,我个人会避免这种做法。

Deal with images as NSData. That's what they are. There are tons of examples online that illustrate how to do this.

将图像作为NSData处理。这是它们是什么。网上有很多例子可以说明如何做到这一点。

One common approach is to upload an image to a web server, then take the URL of the uploaded image and add that to your JSON dictionary, such that your submitted JSON dictionary carries a string representing the URL of the image to download -- not the image itself.

一种常见的方法是将图像上载到web服务器,然后获取上传图像的URL并将其添加到JSON字典中,以便提交的JSON字典携带表示要下载图像的URL的字符串——而不是图像本身。

#3


2  

You can try send UIImage with NSString like this: Swift 3:

你可以尝试用NSString发送UIImage如下:Swift 3:

if let jpegData = UIImageJPEGRepresentation(image, 1.0) {
    var encodedString = jpegData.base64EncodedString()
    var mainJSON = [
        "First_Name" : "John",
        "Last_name" : "McCintosh",
        "Profile_picture" : encodedString
    ]

}

Objective-c:

objective - c:

NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *encodedString = [imageData base64Encoding];


 NSDictionary* mainJSON = [NSDictionary dictionaryWithObjectsAndKeys:
                          @"John",
                          @"First_Name",
                          @"McCintosh",
                          @"Last_name",
                          encodedString,
                          @"Profile_picture",
                          nil];

This is Base64 format so you can decode this in any language

这是Base64格式,所以你可以用任何语言解码它

#4


0  

Okay, Thansk to @tolgamorf and @isaac, I tried using AFNetwork. I could do what I want. It's powerful and simple.

好的,谢谢@tolgamorf和@isaac,我试过使用AFNetwork。我可以做我想做的。这是强大的和简单的。

NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5);
NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"  path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg"  mimeType:@"image/jpeg"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[httpClient enqueueHTTPRequestOperation:operation];

I took the code from official documentation from here .

我从这里拿到了官方文件的代码。

Enjoy

享受