I have ViewController1 and ViewController2.
ViewController1 is UICollectionView and it use ASAssetLibrary to load thumbnail into UICollectionViewCell:
NSMutableArray *collector = [[NSMutableArray alloc] initWithCapacity:0];
ALAssetsLibrary *al = [TemplateEditBarController defaultAssetsLibrary];
[al enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset) {
[collector addObject:asset];
}
}];
assetsarray = collector;//<--assetsarray is local.
}
failureBlock:^(NSError *error) { NSLog(#"fail!");}
];
When cell selected, I want to pass either NSString or NSURL to ViewController2 so that it will call and display the full resolution image. But when NSLog the url:
ALAsset* asset = backgroundsarray[row];
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSURL *url = [representation url];
newbg = [url absoluteString];//<-NSLog this.
I get:
assets-library://asset/asset.JPG?id=6E5438ED-9A8C-4ED0-9DEA-AB2D8F8A9360&ext=JPG
I tried change to [url path] I get:
asset.JPG
How can I get the actual photo url so that I can convert to NSString to pass to ViewController2?
NSURL* aURL = [NSURL URLWithString:imagePath];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:aURL resultBlock:^(ALAsset *asset)
{
UIImage *image = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage] scale:0.5 orientation:UIImageOrientationUp];
imageView.image=image;
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(#"failure-----");
}];
My solution here:
ALAssetsLibrary *assetslibrary = [[ALAssetsLibrary alloc] init];
[assetslibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
if (asset) {
image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
}
}
Apparently there isn't any direct solution other than passing ALAsset. This is what I do:
In ViewController1, which is UICollectionViewController, I have this function:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//NSLog(#"selected row: %ld",(long)indexPath.row);
long row = [indexPath row];
NSString* newbg = [[NSString alloc]init];
if ([bartype isEqualToString:#"photolibrary"]) {
ALAsset* asset = backgroundsarray[row];
[_delegate changeBackgroundWithAsset:asset];
}
Then I have a function in ViewController2 to process ALAsset:
-(void)changeBackgroundWithAsset:(ALAsset*)b{
ALAssetRepresentation *rep = [b defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
UIImage *bimage;
bimage = [UIImage imageWithCGImage:iref];
UIImageView* bgview = [[UIImageView alloc]init];
bgview = curbgview;
bgview.image = bimage;
}
Related
I want to create a custom library where i will get all videos with their folder name. I implemented some code but this is not working properly. My code get videos from some folders but also drop some folder. i want to fetch all folders.
This is my code:-
-(void)getAllVideos
{
assetItems = [NSMutableArray arrayWithCapacity:0];
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
NSString * str = [NSString stringWithFormat:#"%#",group];
int power = [str rangeOfString:#","].location;
NSString *str1= [str substringToIndex:power];
int dash = [str rangeOfString:#":"].location;
NSString *final = [str1 substringFromIndex:dash+1];
combineArray =[[NSMutableArray alloc]init];
thumbnailImages = [[NSMutableArray alloc]init];
videosURL = [[NSMutableArray alloc]init];
NSLog(#"name of folder%#",group);
[groupName addObject:final];
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
AVAsset *asset = [AVAsset assetWithURL:videoURL];
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
CMTime time = [asset duration];
time.value = 0;
CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:NULL];
UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
[thumbnailImages addObject:thumbnail];
[videosURL addObject:videoURL];
}
} ];
if(thumbnailImages.count >0)
[combineArray addObject:thumbnailImages];
if(videosURL.count > 0)
[combineArray addObject:videosURL];
if(combineArray.count>0)
[alldata setObject:combineArray forKey:final];
}
// group == nil signals we are done iterating.
else
{
dispatch_async(dispatch_get_main_queue(), ^{
});
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
}
Please suggest me what changes i have to do?
I have a picture named IMG_0094.JPG, taken by the device's camera.
I would like initialize my UIImageView with it but my code doesn't work.
Following code is in viewDidLoad.
currentImageName = [contact objectForKey:#"image"];
NSURL* aURL = [NSURL URLWithString:currentImageName];
NSLog(#"%#", aURL);
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library assetForURL:aURL resultBlock:^(ALAsset *asset)
{
UIImage *copyOfOriginalImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullScreenImage] scale:0.5 orientation:UIImageOrientationUp];
UIImageView *photo = (UIImageView *)[self.view viewWithTag:TAG_PHOTO];
photo.image = copyOfOriginalImage;
photo.contentMode = UIViewContentModeScaleAspectFit;
}
failureBlock:^(NSError *error)
{
// error handling
NSLog(#"failure---");
}];
My NSLOG return 2015-02-26 10:39:54.899 Fiche Contacts[1600:60b] IMG_0094.JPG
The answer, use the url which is generate when the picture is saved : http://www.to-string.com/2014/04/30/how-to-extract-string-reference-to-an-image-in-ios-and-then-load-the-image-later/
ALAssetsGroupEnumerationResultsBlock assetsEnumerationBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result) {
[assets addObject:result];
ALAssetRepresentation *rep = [result defaultRepresentation];
photoname=[rep filename];
imageurl=[rep url];
NSLog(#"result %#",result);
NSLog(#"name %#",photoname);//Img0001.Jpg
NSLog(#"name %#",imageurl);//assets-library://asset/asset.JPG?id=3B36DBC8-A2F7-4088-ADEF-A9E2FF8FD927&ext=JPG
[print addObject:photoname];
//NsuserDefaults
// NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithArray:print];
// [[NSUserDefaults standardUserDefaults] setObject:mutableArray forKey:#"test"];
retArray = [[NSMutableArray alloc] initWithArray:((NSMutableArray *) [[NSUserDefaults standardUserDefaults] objectForKey:#"test"])];
NSLog(#"res %#",retArray);
}
};
ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
[self.assetsGroup setAssetsFilter:onlyPhotosFilter];
[self.assetsGroup enumerateAssetsUsingBlock:assetsEnumerationBlock];
}
You need to use the assets library to get the asset for the URL, and then get the image from the asset. Currently you are treating the asset URL as an asset rather than using the URL to get the asset:
[self.assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset * asset) {
UIImage *image = [UIImage imageWithCGImage:[asset thumbnail]];
// use the image for something
}
NSURL *assetURL = notequal[indexPath.row];
[self.assetslibrary assetForURL:assetURL resultBlock:^(ALAsset * asset) {
UIImage *image = [UIImageimageWithCGImage[asset thumbnail]];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:kImageViewTag];
imageView.image = thumbnail;
}];
return cell;
I tried below code to get all videos from photo library by using ALAsset. For now, i want to display all videos to a UICollectionview but it doesn't seem to display anything. Please give me some advice. Thanks in advance.
-ViewDidLoad() : get all videos from Photo Library
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[allVideos addObject:dic];
[_collectionView reloadData];
}
}];
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
-imageFromVideoURL():
- (UIImage *)imageFromVideoURL:(NSURL*)videoURL
{
// result
UIImage *image = nil;
// AVAssetImageGenerator
AVAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];;
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
imageGenerator.appliesPreferredTrackTransform = YES;
// calc midpoint time of video
Float64 durationSeconds = CMTimeGetSeconds([asset duration]);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds/2.0, 600);
// get the image from
NSError *error = nil;
CMTime actualTime;
CGImageRef halfWayImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:&error];
if (halfWayImage != NULL)
{
// CGImage to UIImage
image = [[UIImage alloc] initWithCGImage:halfWayImage];
[dic setValue:image forKey:#"name"];
NSLog(#"Values of dictionary==>%#", dic);
NSLog(#"Videos Are:%#",videoURL);
CGImageRelease(halfWayImage);
}
return image;
}
Start to display all thumbnails of video to UICollectionView:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return allVideos.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSLog(#"allvideo %#", allVideos);
ALAsset *alasset = [allVideos objectAtIndex:indexPath.row];
return cell;
}
Replace this Line:-
[allVideos addObject:dic];
With
[allVideos addObject: asset];
And in this method:-
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"cellIdentifier" forIndexPath:indexPath];
NSLog(#"allvideo %#", allVideos);
ALAsset *alasset = [allVideos objectAtIndex:indexPath.row];
yourImageView.image = [UIImage imageWithCGImage:alasset.thumbnail];
}
First of all take the code [_collectionView reloadData] out of the ALAssetsGroupEnumerationResultsBlock (the block you passed to -enumerateAssetsUsingBlock:) as it'll call the -reloadData for all the AVAssets found.
There is a sample app "MyImagePicker" available from apple which does the exact thing you want to do. You can study the working from there.
I need to save path of the image picked from server and later access the path to show that image on user click by database retrival.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
NSString *urlPath = [info objectForKey:#"UIImagePickerControllerReferenceURL"]absoluteString];
}
and saving it to database.
It saved as assets-library://asset/asset.JPG?id=E1136225-97DE-4BF4-A864-67E33D60737A&ext=JPG
then I want to import to Imageview
UIImageView *iv = [[UIImageView alloc]init];
iv.image = [UIimage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagepath]]];
But it is not working
Try this:
typedef void (^ALAssetsLibraryAssetForURLResultBlock)(ALAsset *asset);
typedef void (^ALAssetsLibraryAccessFailureBlock)(NSError *error);
ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset){
ALAssetRepresentation *rep = [myasset defaultRepresentation];
CGImageRef iref = [rep fullResolutionImage];
if (iref){
UIImage *myImage = [UIImage imageWithCGImage:iref scale:[rep scale] orientation:(UIImageOrientation)[rep orientation]];
[fileImage addObject:myImage];
}
};
ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *myerror){
//failed to get image.
};
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
[assetslibrary assetForURL:[filePath objectAtIndex:0] resultBlock:resultblock failureBlock:failureblock];
Note: Make sure your [filePath objectAtIndex:0] will be a NSUrl object. Else convert it to NSUrl
Example:
ALAssetsLibrary* assetslibrary = [[[ALAssetsLibrary alloc] init] autorelease];
NSURL myAssetUrl = [NSURL URLWithString:[filePath objectAtIndex:0]];
assetslibrary assetForURL:myAssetUrl resultBlock:resultblock failureBlock:failureblock];
Use assetForURL:resultBlock:failureBlock: method of ALAssetsLibrary class to retrieve image by URL.
There is more info: http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAssetsLibrary_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40009722
UPD:
ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib assetForURL: url resultBlock: ^(ALAsset *asset) {
ALAssetRepresentation *r = [asset defaultRepresentation];
self.imgView.image = [UIImage imageWithCGImage: r.fullResolutionImage];
}
failureBlock: nil];
Where is url is your cached URL