7

私は使っている

imageData = UIImagePNGRepresentation(imgvw.image);

そして投稿しながら

[dic setObject:imagedata forKey:@"image"]; 

NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&theError];

現在、アプリがクラッシュしています。キャッチされていない例外が原因でアプリを終了しています ' NSInvalidArgumentException'、理由: 'JSON 書き込みの型が無効です (NSConcreteMutableData)

4

3 に答える 3

11

UIImage を NSData に変換してから、その NSData をデータの base64 文字列表現となる NSString に変換する必要があります。

NSData* から NSString* を取得したら、キー @"image" で辞書に追加できます。

NSData を base64 タイプの NSString* に変換するには、次のリンクを参照してください: How do I do base64 encoding on iphone-sdk?

より疑似的な方法では、プロセスは次のようになります

UIImage *my_image; //your image handle
NSData *data_of_my_image = UIImagePNGRepresentation(my_image);
NSString *base64StringOf_my_image = [data_of_my_image convertToBase64String];

//now you can add it to your dictionary
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:base64StringOf_my_image forKey:@"image"];

if ([NSJSONSerialization isValidJSONObject:dict]) //perform a check
{
        NSLog(@"valid object for JSON");
        NSError *error = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];


        if (error!=nil) {
            NSLog(@"Error creating JSON Data = %@",error);
        }
        else{
            NSLog(@"JSON Data created successfully.");
        }
}
else{
        NSLog(@"not a valid object for JSON");
    }
于 2013-08-19T05:47:07.350 に答える
4

これを試して

NSData *imageData  = [UIImageJPEGRepresentation(self.photoImageView.image, compression)  dataUsingEncoding:NSUTF8StringEncoding];

const unsigned char *bytes = [imageData bytes]; 
NSUInteger length = [imageData length];
NSMutableArray *byteArray = [NSMutableArray array];
for (NSUInteger i = 0; i length; i++)
{
    [byteArray addObject:[NSNumber numberWithUnsignedChar:bytes[i]]];
}

NSDictionary *dictJson = [NSDictionary dictionaryWithObjectsAndKeys:
              byteArray, @"photo",
              nil];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictJson options:0 error:NULL];
于 2013-08-19T05:31:08.660 に答える
-3

次のように NSData で画像を変換できます。

PNG画像の場合

UIImage *image = [UIImage imageNamed:@"imageName.png"];
NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];

JPG画像の場合

UIImage *image = [UIImage imageNamed:@"imageName.jpg"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

そして、それをCoreDataに保存することができます.この方法はあなたにとって便利です:-

[newManagedObject setValue:imageData forKey:@"image"];

次のようにロードできます:-

 NSManagedObject *selectedObject = [[self yourFetchCOntroller] objectAtIndexPath:indexPath];
      UIImage *image = [UIImage imageWithData:[selectedObject valueForKey:@"image"]];
// and set this image in to your image View  
    yourimageView.image=image;
于 2013-08-19T05:24:30.233 に答える