从图像网址代表从资产库转到base64

时间:2014-01-03 17:13:02

标签: ios objective-c

我最终尝试将url rep形式的字典中的照片数组转换为base64以通过json发送。

这是字典代码和日志:

    NSDictionary *dict = [self.form dictionaryWithValuesForKeys:keys];
    NSLog(@"dict::%@",dict);

的NSLog:

dict::{   
    boardLodgingFurnished = "<null>";
    caption = "<null>";
    cars = "";
    photos =     (
                {
            caption = "";
            urlRep = "assets-library://asset/asset.JPG?id=CE8A426B-3B59-4172-8761-CC477F3BB3EE&ext=JPG";
        },
                {
            caption = "";
            urlRep = "assets-library://asset/asset.JPG?id=F4B68A42-1CA0-4880-9FB5-177CB091A28C&ext=JPG";
        }
    );
    yearsAtLocation = "";
    yearsInTheBusiness = "";
}

因此,对于字典中的每张照片,我想取urlRep并将其转换为base64字符串,并在字典中将urlRep替换为它。

我现在拥有的......不确定我是否朝着正确的方向前进:

for (id imageURL in [dict objectForKey:@"photos"])
{
ALAssetsLibrary *library = [ALAssetsLibrary new];
            ALAsset *ourAsset = [self assetForURL:imageURL withLibrary:library];

            /* Check out ALAssets */
            NSLog(@"%@", ourAsset);

            ALAssetRepresentation *representation = [ourAsset defaultRepresentation];
            CGImageRef imageRef = [representation fullResolutionImage];

            //TODO: Deal with JPG or PNG
            NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.1);
       NSLog(@"imagedata??%@",      [imageData base64EncodedString]);
//need to know how to add this back to dict
}

从上面调用以下方法,但在

的while循环中崩溃
-[__NSDictionaryI scheme]: unrecognized selector sent to instance 0x166dd090
2014-01-03 10:57:27.361 Inspection App[2728:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryI scheme]: unrecognized selector sent to instance 0x166dd090'

方法

- (ALAsset *)assetForURL:(NSURL *)url withLibrary:(ALAssetsLibrary *)assetsLibrary {
    __block ALAsset *result = nil;
    __block NSError *assetError = nil;
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);

    [assetsLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
        result = asset;
        dispatch_semaphore_signal(sema);
    } failureBlock:^(NSError *error) {
        assetError = error;
        dispatch_semaphore_signal(sema);
    }];


    if ([NSThread isMainThread]) {
        while (!result && !assetError) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    }
    else {
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    }

    return result;
}

修改

if (photoUrls.count) {
            for (id photos in photoUrls){
            NSString *urlString = photos;
            [self base64ImageAtUrlString:urlString result:^(NSString *base64) {

                NSLog(@"imagedata??%@", base64);
            }];
        }
        }
        else {
            NSLog(@"where are my urls?");
        }

        NSMutableDictionary *jsonWithPhotos = [dict mutableCopy];

        [jsonWithPhotos setObject:convertedImages forKey:@"photo64"];
        NSLog(@"jjson photos::%@", jsonWithPhotos);

更新方法

- (void)base64ImageAtUrlString:(NSString *)urlString result:(void (^)(NSString *))completion {
    NSURL *url = [NSURL URLWithString:urlString];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library assetForURL:url resultBlock:^(ALAsset *asset) {

        // borrowing your code, here... didn't check it....
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        CGImageRef imageRef = [representation fullResolutionImage];

        //TODO: Deal with JPG or PNG
        NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.1);
        NSString *base64 = [imageData base64EncodedString];
        completion(base64);
        [convertedImages addObject:base64];

//        NSLog(@"converted::%@",convertedImages);

    } failureBlock:^(NSError *error) {
        NSLog(@"that didn't work %@", error);
    }];
}

当我记录jsonWithPhotos时,对象photo64只是一个空白数组

1 个答案:

答案 0 :(得分:2)

崩溃是由于关于字典的代码中的错误假设。鉴于已解析为json的字典的已发布描述,您需要获取这样的URL:

// collect the photo urls in an array
NSMutableArray *photoUrls = [NSMutableArray array];

// photos is an array of dictionaries in the dictionary
NSArray *photos = dict[@"photos"];
for (NSDictionary *photo in photos) {
    // photo is a dictionary containing a "caption" and a "urlRep"
    [photoUrls addObject:photo[@"urlRep"]];
}

现在,您可以继续使用其作业只是转换的方法。您的问题可能包含更多有关如何执行此操作的问题。我建议开始简单。看看你是否可以进行一次转换。通过反向写入来测试它,从base64返回到图像。

编辑0 :如果不深入检查,我会重新构建您的编码尝试,如下所示:

- (void)base64ImageAtUrlString:(NSString *)urlString result:(void (^)(NSString *))completion {
    NSURL *url = [NSURL URLWithString:urlString];
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    [library assetForURL:url resultBlock:^(ALAsset *asset) {

        // borrowing your code, here... didn't check it....
        ALAssetRepresentation *representation = [asset defaultRepresentation];
        CGImageRef imageRef = [representation fullResolutionImage];

        //TODO: Deal with JPG or PNG
        NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 0.1);
        NSString *base64 = [imageData base64EncodedString];
        completion(base64);

    } failureBlock:^(NSError *error) {
        NSLog(@"that didn't work %@", error);
    }];
}

这样称呼:

if (photoUrls.count) {
    NSString *urlString = photoUrls[0];
    [self base64ImageAtUrlString:urlString result:^(NSString *base64) {
        NSLog(@"imagedata??%@", base64);
    }];
} else {
   NSLog(@"where are my urls?");
}

一旦它正常工作,看看你是否可以逆转它,从base64数据中创建一个图像。最后,一旦完成所有工作,您就可以处理潜在的内存问题。我的建议是考虑一次编码一个,一次一个地发送到服务器并释放它们之间的所有内容。

编辑1 - 每个后续问题,如果你想用base64编码替换url数组中的所有url,它可能会像这样(记住这可能会占用大量内存) ):

- (void)base64ImagesAtUrls:(NSMutableArray *)urls result:(void (^)(void))completion {

    __block NSInteger completed = 0;  // this is how we'll know that we're done
    // this approach doesn't depend on the asset library retrievals completing
    // sequentially, even though they probably will

    for (int i=0; i<urls.count; i++) {
        NSString *urlString = urls[i];
        [self base64ImageAtUrlString:urlString result:^(NSString *base64) {
            [urls replaceObjectAtIndex:i withObject:base64];
            if (++completed == urls.count) completion();
        }];
    }
}
相关问题