从NSData中的电影获取缩略图

时间:2015-10-12 19:25:07

标签: ios objective-c nsdata

我的应用程序允许用户从ELCImagePickerController中选择一个视频,然后将该视频存储在NSData中。下面是我用来获取NSData的代码。

if ([mediaType isEqualToString:@"ALAssetTypeVideo"]) {

        ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
        [assetLibrary assetForURL:[[info objectAtIndex:x] valueForKey:UIImagePickerControllerReferenceURL] resultBlock:^(ALAsset *asset) {

            ALAssetRepresentation *rep = [asset defaultRepresentation];

            unsigned long DataSize = (unsigned long)[rep size];

            Byte *buffer = (Byte*)malloc(DataSize);
            NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:DataSize error:nil];
            NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];//this is NSData may be what you want

            [self.imagesToUpload addObject:data];
            [self.collectionView reloadData];

        } failureBlock:^(NSError *err) {
            NSLog(@"Error: %@",[err localizedDescription]);
        }];  
}

然后我调用此函数从电影的NSData中检索缩略图,但是movieURL总是返回nil ..

- (UIImage *)imageFromMovie:(NSData *)movieData {

    // set up the movie player
    NSString *dataString = [[NSString alloc] initWithData:movieData encoding:NSUTF16StringEncoding];
    NSURL *movieURL = [[NSURL alloc] initWithString:dataString];

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:movieURL options:nil];
    AVAssetImageGenerator *generate = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    NSError *err = NULL;
    CMTime time = CMTimeMake(1, 60);
    CGImageRef imgRef = [generate copyCGImageAtTime:time actualTime:NULL error:&err];
    NSLog(@"err==%@, imageRef==%@", err, imgRef);

    return [[UIImage alloc] initWithCGImage:imgRef];

}

1 个答案:

答案 0 :(得分:0)

对于包含非法字符(如空格)的网址,NSURL将返回nil。检查是否有。我想你需要使用 - [NSString stringByAddingPercentEscapesUsingEncoding:]。

 NSString *urlString = [[NSString alloc] initWithData: movieData encoding:NSUTF8StringEncoding];
 NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];